Uploading file with metadata
Could you help me for how to add a file to the Sharepoint document library? I found some articles in .NET, but I didn't get the complete concept of how to accomplish this.
I uploaded a file without metadata by using this code:
if (fuDocument.PostedFile != null)
{
if (fuDocument.PostedFile.ContentLength > 0)
{
Stream fileStream = fuDocument.PostedFile.InputStream;
byte[] byt = new byte[Convert.ToInt32(fuDocument.PostedFile.ContentLength)];
fileStream.Read(byt, 0, Convert.ToInt32(fuDocument.PostedFile.ContentLength));
fileStream.Close();
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb webcollection = site.OpenWeb())
{
SPFolder myfolder = webcollection.Folders["My Library"];
webcollection.AllowUnsafeUpdates = true;
myfolder.Files.Add(System.IO.Path.GetFileName(fuDocument.PostedFile.FileName), byt);
}
}
}
}
开发者_如何学Go
This code is working fine as is, but I need to upload a file with metadata. Please help me by editing this code if it is possible. I created 3 columns in my document library.
SPFolder.Files.Add returns a SPFile object
SPFile.Item returns an SPListItem object
You can then use SPlistItem["FieldName"] to access each field (see bottom of SPListItem link)
So adding this into your code (this is not tested, but you should get the idea)
SPFile file = myfolder.Files.Add(System.IO.Path.GetFileName(document.PostedFile.FileName);
SPListItem item = file.Item;
item["My Field"] = "Some value for your field";
item.Update()
There is also an overload where you can send in a hashtable with the metadata you want to add. For example:
Hashtable metaData = new Hashtable();
metaData.Add("ContentTypeId", "some CT ID");
metaData.Add("Your Custom Field", "Your custom value");
SPFile file = library.RootFolder.Files.Add(
"filename.fileextension",
bytearray,
metaData,
false);
精彩评论