2

So I'm trying to upload a file, or multiple files, to a sharepoint as attachments to a list item. I have the code to upload the actual files but they're corrupt/unopenable when trying to access them in sharepoint.

I receive these files from an outside API in the form of:

{
    "File": {
        "contentType": ~~~~
        "fileContent": ~~~~
        "name": ~~~~.docx/.pdf
    }
}

I currently am trying to upload it like this:

spClient.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");

foreach (var file in data["files"])
{
    var requestString = $"{siteUrl}/lists('{listID}')/items('{siteResponseObject["id"]}')/AttachmentFiles/add(FileName='{file["File"]["name"]}')";
    StringContent filePostData = new StringContent(file["File"]["fileContent"].ToString(), Encoding.UTF8, file["File"]["contentType"].ToString());
    var filePost = await spClient.PostAsync(requestString, filePostData);
}

The contentType of each file varies, while testing for example, I get back these file types:

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/pdf

siteResponseObject is the response from creating the listItem which contains it's ID and everything.

Does the sharepoint API expect to like a byte array? Am I encoding the StringContent object wrong?

1 Answer 1

1

Most likely, you receive the fileContent as base64 string from the external service. So first, you must convert it into a stream and then post the stream in the body:

spClient.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");

foreach (var file in data["files"])
{
    var bytes = Convert.FromBase64String(file["File"]["fileContent"]);
    var content = new StreamContent(new MemoryStream(bytes));

    var requestString = $"{siteUrl}/lists('{listID}')/items('{siteResponseObject["id"]}')/AttachmentFiles/add(FileName='{file["File"]["name"]}')";
    var filePost = await spClient.PostAsync(requestString, content);
}
1
  • That worked perfectly. Thank you.
    – KFrancis
    Commented Sep 12, 2019 at 16:57

Your Answer

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

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