Monday, 9 June 2014

SharePoint 2010: How do I load a picture and meta data to an asset library?

I recently had to load some seed data for a SharePoint site that required the population of some images into an asset library. After a lot of playing and experimenting, I eventually settled on the pattern of

1. Add the files to an image folder in the Style Library
2. Reading in the source file into a byte array
3. then loading the array into a new file in the target location.

Its a little convoluted, but it was the only solution that met my requirement.

I then populated a dictionary with a name/value pair that mapped to the columns in my content type.

Here are the methods I used:

     public void UploadFile(SPWeb webParam, string fileUrl, SPList list, Dictionary<string, string> parameters)
        {
            try
            {
             
                using (SPSite site = new SPSite(webParam.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        //SPList list = web.Lists.TryGetList(listName);

                        string urlOfFile = string.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, Path.GetFileName(fileUrl));
                        string title = Path.GetFileName(fileUrl).Substring(0, Path.GetFileName(fileUrl).IndexOf("."));

                        using (Stream file = (new WebClient() { Credentials = CredentialCache.DefaultCredentials }).OpenRead(fileUrl))
                        {
                            byte[] b = ReadFully(file);

                            using (MemoryStream DocumentStream = new MemoryStream())
                            {
                                using (StreamWriter writer = new StreamWriter(DocumentStream))
                                {
                                    writer.Write(b);
                                    writer.Flush();
                                    SPFile file2 = list.RootFolder.Files.Add(Path.GetFileName(fileUrl), DocumentStream, true);
                                    file2.Update();
                                    list.Update();
                                }
                            }
                        }

                        SPListItem uploadedFile = web.GetListItem(urlOfFile);
                        if (uploadedFile != null)
                        {
                            // for the hyperlink
                            SPFieldUrlValue urlValue = new SPFieldUrlValue();
                            urlValue.Description = title;
                            urlValue.Url = fileUrl;
                            uploadedFile["AlternateThumbnailUrl"] = urlValue;

                            foreach (var i in parameters)
                            {
                                uploadedFile[i.Key] = i.Value;
                            }

                            uploadedFile.Update();
                        }
                        else throw new Exception("Something bad happened!");
                    }
                }

            }
            catch (Exception ex)
            {
                // handle exception here
            }
        }

        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

And here is the invocation:

string sourceFile = "http://SiteCollection/Site/Style%20Library/myimage.png";

Dictionary<string, string> parameters = new Dictionary<string,string>();
parameters.Add("Title", "My Test Title");
parameters.Add("MyCustomColumn", "Foo");

UploadFile(web, sourceFile, web.Lists["MyList"], parameters);

No comments:

Post a comment