Prerequisites

We need to have the AJAX Control toolkit installed.

  1. Create an ASP.NET web application.



  2. Add SharePoint DLL References. These references can be found in “C:\Program Files\Common Files\Microsoft shared\Web Server Extensions\15\ISAPI”.

    In order to have this dll you need to install SharePoint Client SDK “https://www.microsoft.com/en-us/download/details.aspx?id=35585”



  3. Now on your web form, you need to drag AjaxFileUpload Controland ScriptManager.



  4. Now on OnUploadComplete create an Event.



    And paste the following code.
    1. protectedvoidOnUploadComplete(object sender, AjaxFileUploadEventArgs e)
    2. {
    3. try
    4. {
    5. //gets the filename
    6. stringfileName = Path.GetFileName(e.FileName);
    7. //gets the temporary location of file and ID of folder where files are stored in temporary folder
    8. string path = Path.Combine(Path.GetTempPath(), "_AjaxFileUpload", e.FileId);
    9. //store the path in Sessio
    10. Session["FileDirectory"] = path;
    11. //get the site
    12. ClientContext context = newClientContext(siteUrl);
    13. //get the web object
    14. WeboWebsite = context.Web;
    15. context.Load(oWebsite);
    16. //execute the web object
    17. context.ExecuteQuery();
    18. //get the current list
    19. ListCurrentList = context.Web.Lists.GetByTitle(listName);
    20. context.Load(CurrentList.RootFolder);
    21. context.ExecuteQuery();
    22. //form the url to get the entire path of file like D://folder/test.txt
    23. StringfileURL = (path + "\\" + fileName);
    24. using(FileStreamfileStream = newFileStream(fileURL, FileMode.Open))
    25. Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, CurrentList.RootFolder.ServerRelativeUrl.ToString() + "/" + e.FileName, fileStream, true);
    26. }
    27. catch (Exception ex)
    28. {
    29. lblError.Text = ex.ToString();
    30. lblError.BackColor = System.Drawing.Color.Red;
    31. lblError.ForeColor = System.Drawing.Color.White;
    32. }
    33. finally
    34. {
    35. //delete files from temp folder
    36. e.DeleteTemporaryData();
    37. }
    38. }
  5. Now run the application.






    Files are now uploaded to SharePoint.