Click here to monitor SSC

Programmatically uploading an image to a SharePoint Picture Library

Published 21 October 2009 7:54 am

SharePoint’s ability to store and maintain libraries of resources (such as images, documents and other files) is a very useful weapon in a SharePoint developer’s arsenal. In this article I will show how you can leverage the power of a Picture Library to store uploaded content for use across your Site Collection.

It’s fairly simple to navigate to the user interface for a picture library and upload a new file. It is almost as simple as clicking ‘Upload Picture’ from the Upload menu. However you will additionally be encouraged to add meta-data to your picture in order to better catalogue it.

Uploading a picture

However when you are writing a custom SharePoint solution like a web part or an application page you may not want the user to have to navigate away from your solution in order to upload the image into the requisite picture library. Luckily the SharePoint object model combined with some fairly simple ASP.Net code can simplify this task for you.

The basic concept is simple you take a standard ASP.Net FileUpload control and add this in to your solution. This control provides the basic user interface needed to upload a file and it has some very useful methods for working with the file once it has been uploaded.

The FileUpload control

In addition to this control you will need some ASP.Net code in order to retrieve the contents of this file and some simple Windows SharePoint Services (WSS) 3.0 code to place this picture in the requisite picture library.

You will need to access a Stream of the data from the file uploaded in the FileUpload control. This can then be used to create a new document in the Picture Library. The FileUpload control has a handy property called PostedFile which will provide access to the file which is being uploaded and in turn this has a property called InputStream which contains the Stream of data from the file. Some simple code to achieve this would be:

Dim streamImage As Stream = Nothing
If fleInput.HasFile Then
    streamImage = fleInput.PostedFile.InputStream
End If

The HasFile property of the FileUpload control is fairly self explanatory as it merely indicates if a file has been selected in the control.

The SPPictureLibrary class in WSS 3.0 is dedicated to managing the resources held within a picture library; essentially this is identical to the SPDocumentLibrary class with the addition of 3 properties (ThumbnailSize, WebImageHeight and WebImageWidth) which control how the images display within this picture library. Although this class exists there is no need to use it unless you are interested in dealing with one of those 3 properties. In fact your code only requires the RootFolder property on the SPList class.

The RootFolder property is an instance of the SPFolder class and this provides access to the SPFileCollection which represents the files in this library. So uploading a new file is a case of adding a new SPFile instance into this collection. The code for this would be as shown below:

Using Site As New SPSite("SITECOLLECTIONURL")
    Using Web As SPWeb = Site.OpenWeb("SITEURL")
        Dim pics As SPList = Web.Lists("PICTURELIBRARYNAME")
        pics.RootFolder.Files.Add( _
           
fleInput.FileName, streamImage)
    End Using
End Using

Essentially you are adding the Stream as a new file to your picture library. In actual fact because this code is operating at such a low level you can use it to upload any file into a document library within SharePoint.

Image uploaded

This article has shown how you can use a simple FileUpload control and the power of WSS 3.0 to simplify the uploading of files into Picture Libraries and other SharePoint document libraries.

13 Responses to “Programmatically uploading an image to a SharePoint Picture Library”

  1. student says:

    Hi Charles,
    Thanks for the tutorial, it works fine and perfectly well. I am trying to add ‘Title’ and ‘Description’ along with the newly added picture to the picture library via a small form on a web part (where all the controls are using the code you highlighted). But I just can’t seem to write anything on ‘Title’ and ‘Description’ field of picture library. Can you throw some light into this??

    Using Site As New SPSite(“SITECOLLECTIONURL”)
    Using Web As SPWeb = Site.OpenWeb(“SITEURL”)
    Dim pics As SPList = Web.Lists(“PICTURELIBRARYNAME”)
    Dim newItem as SPListItem = pics.items.add()
    pics.RootFolder.Files.Add( _
    fleInput.FileName, streamImage)
    End Using
    End Using
    newItem(“Title”) = “Test Title”
    newItem(“Description”) = “Test Description”

    Why is this not working??? What am I doing wrong? Is picture library not a normal list type? so why only picture uploads but nothing adds into the title and description field?

    Please help

  2. CharlesLee says:

    You would need to call newItem.update() in order to persist your changes to the actual list item.

  3. student says:

    Many thanks for your reply and taking time out. I did use the
    newItem.Update() command before sorry forgot to put that in the code. It does not work at all. Would you please try to do this and see if it works for you.

    Now in the mean time, because it did not work for me, I ended up creating a custom list to mimic picture library but this has lead to a problem as well. Thumnnail facility of picture library..which reduces image to a small size. Trying to figure out how to go about doing this. If only adding entry to the picture library would work in the first place. Please do give it a try.

    Appreciate your time..

  4. CharlesLee says:

    Apologies, having looked at your code again it doesn’t look like it should work. The item that you are creating in that list is not related to your uploaded picture. You need to access the list item associated with the file.

    I have not tested this but try this:

    Using Site As New SPSite(“SITECOLLECTIONURL”)
    Using Web As SPWeb = Site.OpenWeb(“SITEURL”)
    Dim pics As SPList = Web.Lists(“PICTURELIBRARYNAME”)
    Dim pic As SPFile = pics.RootFolder.Files.Add( _
    fleInput.FileName, streamImage)
    pic.Item(“Title”) = “Test Title”
    pic.Item(“Description”) = “Test Description”
    pic.Update()
    End Using
    End Using

  5. student says:

    Thanks for returning on this.

    ***** SMASHING

    You know what this means – it works..!

    You are right, how would my code work when I am not even making a reference to the Pic recently added and making a mistake of just using standard SPList item update as you would do in normal splist programming. Can’t believe it.
    Many thanks for taking out time to get back to me.

    Please continue uploading more useful stuff.

  6. sirjamescallaghan says:

    Hi Charles, this is perfect what something I am working on.

    I’ve only done development in SP Designer to date. I have a custom form ready and waiting and also a library created.

    Could you provide me some additional steps as to how to utilise your code.

    Thanks,
    James Callaghan

  7. CharlesLee says:

    James,

    Unfortunately this is server side code and would need to be developed and deployed within a custom sharepoint solution using Visual Studio.

    It’s the sort of code you could use within a web part, application page, event receiver or a custom workflow.

    Charlie

  8. student says:

    Hi Charlie,

    Confused again. Now, considering if I want to rename the image file before actually saving it to the picture library, How do we do that?

    fileUpload.SaveAs() and fileUpload.PostedFile.SaveAs() methods require a rooted path eg C:My DocumentsImages and does not accept http://url/someurl that would point to our picture library; where both methods can help in renaming a file to eg
    Dim ext As String = Path.GetExtension(fileUpload.PostedFile.FileName)
    fileUpload.SaveAs((howtosetthispath + “Test”) + ext)

    Also, the following line of code -

    pics.RootFolder.Files.Add(fleInput.FileName, streamImage)

    picks the name of the file on the fileUpload control

    How can we rename the file and then save the image to picture library? Any ideas or possible workarounds?

    Thanks,

  9. CharlesLee says:

    student – calling the SaveAs method is going to try to save the file locally, this is not what you want. In the add method just exchange the fleInput.FileName with your new filename.

    If you are expecting the user to provide a new name then you will need to give them an additional control to specify this as all the FileUpload control will give you is the original filename.

    Hope this helps.

  10. student says:

    Charlie,

    You have no idea, I have gone great lenghts to chase this one up. Using FileUpload from streamImage, FileStream, FileContents, RootFoler.items.add(splist.rootfolder.url + whatever) etc etc. Unbelieveable..!

    Yes, I think I forgot that saveAs() property would work in a standard asp.net site not with sharepoint lists. I don’t have to worry about providing users to rename the file as that is being taken care of inside the code which follows a strict naming convention.

    Thanks so much. Awesome…!

  11. eddygonzalez2000 says:

    Hi, I am trying to upload a file to a sharepoint document Library with your code but the files gets uploaded to the RootFolder of the site and the List of the document Library appears in blank, the code that I am using is this

    using (SPSite oSite = new SPSite(“http://servidor/sitios/IT/PruebaReuniones/aa1/”))
    {
    using (SPWeb oWeb = oSite.OpenWeb())
    {
    if (System.IO.File.Exists(archivo))
    {
    SPList spList = oWeb.Lists["Docs"];

    string fileName = archivoSoloNombre;
    FileStream fileStream = null;
    Byte[] fileContent = null;

    string docPath = archivo; //physical location of the file
    fileStream = File.OpenRead(archivo);
    fileContent = new byte[Convert.ToInt32(fileStream.Length)];
    fileStream.Read(fileContent, 0, Convert.ToInt32(fileStream.Length));
    SPFile archivoSubir = spList.RootFolder.Files.Add(archivoSoloNombre, fileContent);
    archivoSubir.Item["Title"] = archivoSoloNombre;
    archivoSubir.Item["Description"] = “Descripcion”;
    archivoSubir.Update();

    }
    }

    }

    Thanks

  12. safri4u says:

    Thank you so much Mr. CharlesLee, you really made my day!

  13. prijijohn says:

    Hello Charles,

    Can you please help me in this.

    using (SPSite site = new Microsoft.SharePoint.SPSite(SPContext.Current.Site.Url))
    {
    using (SPWeb web = site.OpenWeb())
    {
    web.AllowUnsafeUpdates = true;
    Stream StreamImage = null;
    if (FileUpload1.HasFile)
    {
    StreamImage = FileUpload1.PostedFile.InputStream;
    }
    SPList pics = web.Lists["ORG_IMAGES"];
    SPFile spfile = pics.RootFolder.Files.Add(FileUpload1.FileName, StreamImage);

    spfile.Item["Title"] = “titlee”;
    spfile.Item["Description"] = “testtt”;
    spfile.Item["TOD_ID"] = “3″;
    spfile.Update();

    Image is uploading but the Title,Description and TOD_ID is not showing anything in the Picture Library.Whats the issue.

Leave a Reply