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

  • 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. – Atish Dipongkor - MVP Feb 3 '16 at 13:56
  • I am deploying farm solution.. – KumarV Feb 3 '16 at 17:43
  • In SharePoint Online??? – Atish Dipongkor - MVP Feb 3 '16 at 18:40
  • NO, its on-premises – KumarV Feb 4 '16 at 3:33
  • On which line you are getting error? – P S Feb 4 '16 at 5:29
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, privacy policy and cookie policy

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