# Creating Visual Web part for file upload

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())
{
Boolean replaceExistingFiles = true;
{
byte[] contents = new byte[fStream.Length];
fStream.Close();
string destUrl = SPContext.Current.Web.Url + "/" + DocumentLibName + "/" + Filename;

}
else {
}
}
}
});
}


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

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).