I am trying to create a visual web part to upload documetns using FileUpload control. Below is the working code for uploading a file.
protected void UploadButton_Click(object sender, EventArgs e)
{
string DocumentLibName = "Shared Documents";
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite objsite = new SPSite("http://demo:13121/VisualWebParts/"))
{
using (SPWeb objWeb = objsite.OpenWeb())
{
objWeb.AllowUnsafeUpdates = true;
Boolean replaceExistingFiles = true;
if (FileUploadControl.PostedFile != null)
{
Stream fStream = FileUploadControl.PostedFile.InputStream;
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
string Filename = FileUploadControl.FileName;
string destUrl = SPContext.Current.Web.Url + "/" + DocumentLibName + "/" + Filename;
objWeb.Files.Add(destUrl, contents, replaceExistingFiles);
}
else {
}
objWeb.AllowUnsafeUpdates = false;
}
}
});
}
Now I need to upload files to list in the attachment column. It doesnt work when I replace the DocumentLibName as the list name. It gives an error that the There is no file with URL "https://xyz/"
FileUploadControldoes not work in sandboxed solution. It requires farm solution. So better you can consider CSOM.