0

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/"

5
  • Are you deploying sand-boxed solution? It seems sandboxed as the environment is SPO. FileUploadControl does not work in sandboxed solution. It requires farm solution. So better you can consider CSOM. Commented Feb 3, 2016 at 13:56
  • I am deploying farm solution..
    – KumarV
    Commented Feb 3, 2016 at 17:43
  • In SharePoint Online??? Commented Feb 3, 2016 at 18:40
  • NO, its on-premises
    – KumarV
    Commented Feb 4, 2016 at 3:33
  • On which line you are getting error?
    – P S
    Commented Feb 4, 2016 at 5:29

1 Answer 1

1

Adding attachments to list items is completely different than uploading files to a doc lib.
You first need to get a reference to the SPPListItem you want to attach to, and then you use myListItem.Attachments.Add.
Here's a sample of code that may help you: it attaches multiple files (from local drive instead than from the UplaodFile control, but the story is the same).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.