I have a form which has a formview. i want to include a fileupload control to upload files into a sharepoint repository and save the uploaded files as ID_1,ID_2 etc. I am new to asp.net. I need help on how to do this
2 Answers
You can upload file to sharepoint using Client object model :
public void UploadFileToSharePoint(string filePath)
{
ClientContext context = new ClientContext("yoursite");
Web web = context.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(filePath);
newFile.Url = System.IO.Path.GetFileName(filePath);
List docs = web.Lists.GetByTitle("LibName");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
context.Load(uploadFile);
context.ExecuteQuery();
}
After you can update the listitem with your required ID or you can attach a item updating event handler to update the Title of your file.
Comments
private static void UploadBtn_click(Object sender, EventArgs e)
{
using (SPSite osite = new SPSite("URL"))
{
using (SPWeb oWeb = osite.OpenWeb())
{
oWeb.AllowUnsafeUpdates = true;
SPList list = oWeb.TryGetList("ListName");
SPListItem item = list.AddItem();
FileStream stream = new FileStream(UploadBtn.FileName, FileMode.Open) ;
byte[] byteArray = new byte[stream.Length];
stream.Read(byteArray, 0, Convert.ToInt32(stream.Length));
stream.Close();
//read Last item ID here refer my 2nd link bellow
item.Attachments.Add("ID_1.doc", byteArray);
item["Title"] = TextBox1.Text;
item.Update();
oWeb.AllowUnsafeUpdates = false;
}
}
}
One more way to upload 1)http://msdn.microsoft.com/en-us/library/lists.lists.addattachment.aspx