0

I'm uploading to sharepoint using a c# client, and every file I Upload gets extra data included. A one line CSV file gets turned into a 7 line file that isn't usable. This is what my one line file upload turned into:

-----------AEE7A299-297A-41E0-B1CC-A72050FCDD28 
Content-Disposition: form-data; name="ControlFile_RCTI_statement_20220218_145832.csv"; filename="ControlFile_RCTI_statement_20220218_145832.csv"    
Content-Type: application/octet-stream  

File;Class;Account Number;Effective Date;Product;Account Type;Document Name 

-----------AEE7A299-297A-41E0-B1CC-A72050FCDD28--   

My upload code is using restSharp

public async Task UploadFile(string filePath, string list, string folderPath)
{
    await CheckTokenAsync();
    var fileName = Path.GetFileName(filePath);
    var endpoint = $"{spCredentials.sharepointSubSiteFullUrl}/_api/web/GetFolderByServerRelativeUrl('{list}/{folderPath}')/Files/Add(url='{fileName}', overwrite=false)";
    var client = new RestClient(endpoint);
    client.Timeout = 30000;
    var request = new RestRequest(Method.POST);
    request.AddHeader("Authorization", $"Bearer {token}");
    request.AddHeader("Accept", "application/json;odata=verbose");
    request.AddFile(fileName, filePath);
    var response = await client.ExecuteAsync(request);
    if (response.StatusCode == HttpStatusCode.OK)
    {
        var fileData = JsonConvert.DeserializeObject<SPSingleResultContainer>(response.Content);
        var link = fileData.d.__metadata.uri;
        await SendRequest<string>($"{link}/CheckIn()", Method.POST);
    }
    else
        throw new Exception($"Upload Failed with message: " + response.ErrorMessage);
}

I've also added this question to the sharepoint SE at https://sharepoint.stackexchange.com/questions/300550/uploading-files-to-sharepoint-with-restsharp-and-their-rest-api-is-adding-header

1 Answer 1

0

Turned out RestSharp was doing a multipart upload, and sharepoint doesn't like that sort of thing. Other people have had This Issue with RestSharp

public async Task UploadFile(string filePath, string list, string folderPath)
{
    var bytes = File.ReadAllBytes(filePath);
    await UploadFileData(Path.GetFileName(filePath), list, folderPath, bytes);
    return;
}
public async Task UploadFileData(string fileName, string list, string folderPath, byte[] fileData)
{
    await CheckTokenAsync();
    var endpoint = $"{spCredentials.sharepointSubSiteFullUrl}/_api/web/GetFolderByServerRelativeUrl('{list}/{folderPath}')/Files/Add(url='{fileName}', overwrite=false)";
    var client = new RestClient(endpoint);
    client.Timeout = 30000;
    var request = new RestRequest(Method.POST);
    request.AddHeader("Authorization", $"Bearer {token}");
    request.AddHeader("Accept", "application/json;odata=verbose");
    string contentType = "";
    var fileType = Path.GetExtension(fileName).ToLower();
    switch (fileType)//there are better ways to get the MIME type, I was just getting desperate and trying everything
    {
        case ".csv":
            contentType = "text/csv";
            break;
        case ".xlsx":
            contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            break;
        case ".pdf":
            contentType = "application/pdf";
            break;
        case ".html":
            contentType = "text/html";
            break;
        default:
            throw new NotImplementedException($"File type {fileType} not supported");
    }
    request.AddHeader("Content-Type", contentType);
    request.AddParameter(contentType, fileData, ParameterType.RequestBody);

    var response = await client.ExecuteAsync(request);

    var test = JsonConvert.SerializeObject(request);
    if (response.StatusCode == HttpStatusCode.OK)
    {
        var fileMetaData = JsonConvert.DeserializeObject<SPSingleResultContainer>(response.Content);
        var link = fileMetaData.d.__metadata.uri;
        await SendRequest<string>($"{link}/CheckIn()", Method.POST);
    }
    else
        throw new Exception($"Upload {fileName} Failed with status {response.StatusCode} and message: " + response.ErrorMessage);
}

For anyone coming here that doesn't care about sharepoint, replacing .addfile with

request.AddHeader("Content-Type", contentType);
request.AddParameter(contentType, fileData, ParameterType.RequestBody);

where contentType is the MIME format of your file extension (or an empty string seems to work as well) solved the issue for me.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.