-9

I have a Web Form that uploads some inputted data to a SharePoint list as a new list item which works well. I tried to add a new code to upload two files via two separate <asp:FileUpload> controls. The following code in protected void sendToSharePoint() {} does not work to upload either file to the specified SharePoint document library, let alone both:

Default.aspx:

//Existing code

<asp:FileUpload ID="upldGradeReport" runat="server" />
<asp:FileUpload ID="upldExpenseReceipt" runat="server" />

<asp:Button ID="btnSubmitForm" OnClick="SubmitButton_Click" runat="server" Text="Submit" />

Default.aspx.cs:

using System;
using System.DirectoryServices;
using System.IO;
using System.Security;
using System.Web.UI;
using Microsoft.SharePoint.Client;
using ClientOM = Microsoft.SharePoint.Client;

//I left out the NameSpace and default public partial class wrapper, but they're here.

public ClientContext SPClientContext { get; set; }
public string SPErrorMsg { get; set; }

protected void SubmitButton_Click(object sender, EventArgs e) {
    sendToSharePoint();
    Response.BufferOutput = true;
    Response.Redirect("Submission.aspx");
}

protected void sendToSharePoint() {

    try {
        string siteUrl = "<sharepoint site url>";

        ClientContext clientContext = new ClientContext(siteUrl);
        clientContext.Credentials = new SharePointOnlineCredentials("<my username>", "<my password>");

        string sDocName = string.Empty;
        string sDocName1 = string.Empty;
        Uri uri = new Uri(siteUrl);
        string sSPSiteRelativeURL = uri.AbsolutePath;
        sDocName = UploadFile(upldGradeReport.FileContent, upldGradeReport.FileName, sSPSiteRelativeURL, "<sharepoint document library>");
        sDocName1 = UploadFile(upldExpenseReceipt.FileContent, upldExpenseReceipt.FileName, sSPSiteRelativeURL, "<sharepoint document library>");

        //prior CSOM code to insert values into a new List Item exists here

        clientContext.ExecuteQuery();
    } catch (Exception ex) {
        String ThisError = ex.Message;
    }
}

public String UploadFile(Stream fs, string sFileName, string sSPSiteRelativeURL, string sLibraryName) {
    string sDocName = string.Empty;
    try {
        var sFileURL = String.Format("{0}/{1}/{2}", sSPSiteRelativeURL, sLibraryName, sFileName);
        ClientOM.File.SaveBinaryDirect(SPClientContext, sFileURL, fs, true);
        sDocName = sFileName;
    } catch (Exception ex) {
        sDocName = string.Empty;
        SPErrorMsg = ex.Message;
    }
    return sDocName;
}

The code that creates a new ListItem and uploads the rest of the form's inputted data to it on a separate SharePoint list still works upon submission, and I've confirmed the credentials are correct and the account being used has privileges to upload files to the Document Library.

What am I doing wrong?

TylerH
  • 20,799
  • 66
  • 75
  • 101

1 Answers1

0

I tested the below code in my local environment; it works fine.

<div>
    <asp:FileUpload ID="upldGradeReport" runat="server" />
    <asp:FileUpload ID="upldExpenseReceipt" runat="server" />

    <asp:Button ID="btnSubmitForm" OnClick="SubmitButton_Click" runat="server" Text="Submit" />
</div>


protected void SubmitButton_Click(object sender, EventArgs e)
{
    sendToSharePoint();
    Response.BufferOutput = true;
    Response.Redirect("Submission.aspx");
}

protected void sendToSharePoint()
{

    try
    {
        string siteUrl = "https://tenant.sharepoint.com/sites/lee";

        ClientContext clientContext = new ClientContext(siteUrl);
        SecureString securePassword = new SecureString();
        foreach (char c in "password".ToCharArray()) securePassword.AppendChar(c);
        clientContext.Credentials = new SharePointOnlineCredentials("lee@tenant.onmicrosoft.com", securePassword);                
        string sDocName = string.Empty;
        string sDocName1 = string.Empty;
        Uri uri = new Uri(siteUrl);
        string sSPSiteRelativeURL = uri.AbsolutePath;
        sDocName = UploadFile(clientContext,upldGradeReport.FileContent, upldGradeReport.FileName, sSPSiteRelativeURL, "MyDoc");
        sDocName1 = UploadFile(clientContext,upldExpenseReceipt.FileContent, upldExpenseReceipt.FileName, sSPSiteRelativeURL, "MyDoc");

        //prior CSOM code to insert values into a new List Item exists here

        //clientContext.ExecuteQuery();
    }
    catch (Exception ex)
    {
        String ThisError = ex.Message;
    }
}

public String UploadFile(ClientContext clientContext,Stream fs, string sFileName, string sSPSiteRelativeURL, string sLibraryName)
{
    string sDocName = string.Empty;
    try
    {
        var sFileURL = String.Format("{0}/{1}/{2}", sSPSiteRelativeURL, sLibraryName, sFileName);

        Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, sFileURL, fs, true);
        sDocName = sFileName;
    }
    catch (Exception ex)
    {
        sDocName = string.Empty;
        //SPErrorMsg = ex.Message;
    }
    return sDocName;
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Lee
  • 5,305
  • 1
  • 6
  • 12
  • 1
    Going through this now; I see you've added a `ClientContext` argument to `UploadFile()`... can you explain why and/or link to some documentation that explains that? – TylerH Apr 10 '19 at 14:23
  • 5
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – double-beep Apr 10 '19 at 18:38
  • Just reuse ClientContext, if you init ClientContext form page load or other method, don't need pass to UploadFile function. – Lee Apr 11 '19 at 01:03
  • Just a late note for my own reference and anyone else who happens upon this code; I replaced the `upldGradeReport.FileName` (and `upldExpenseReceipt.FileName` with a combined string of other variables plus strings demarcated in quotes, and it uploaded "unknown file types" to SharePoint. So if one does expand on the name parameter, be sure to account for that (I accounted for it by getting the file extension of the filename via `.substring` and `.lastindexof` and then adding that to the end of my concatenated file name parameter. – TylerH Jun 03 '20 at 21:09