I am currently trying to upload a file from Business Central to SharePoint using the REST API. For the sake of simplicity, I first took a picture. I converted this image to BASE64 and attached it to my JSON body. The problem is that SharePoint does not decode the text correctly and accordingly displays the file as unreadable. When I upload the file as .txt, I can see the JSON text. When I decode this BASE64 code into an image, I can obviously see the correct image. Later for more simplicity i took a .txt file and tried it with this file, still the same issue. I can read the file now, but the content is still the undecoded (that would be encoded again) base64 string.

Can't Sharepoint decode JSON data or am I missing something? I use Business Central and therefore work with AL Code. Attached you can see my AL Code Snippet.

local procedure UplaodFileViaREST()
    selectedFile: Text;
    instr: InStream;
    fileMgmt: Codeunit "File Management";
    fileName: Text;
    fileExt: Text;
    Client: HttpClient;
    Content: HttpContent;
    HttpHeadersContent: HttpHeaders;
    body: TextBuilder;
    bodyText: Text;
    base64Convert: Codeunit "Base64 Convert";
    uri: Text;
    jso: JsonObject;
    response: HttpResponseMessage;
    RespMess: Text;
    Link: TextBuilder;
    RelativePathHelper: Text;
    UploadIntoStream('Select a file to upload', '', '', selectedFile, instr);
    fileName := fileMgmt.GetFileNameWithoutExtension(selectedFile);
    fileExt := fileMgmt.GetExtension(selectedFile);
    uri := 'https://myCompany.sharepoint.com/sites/WSTesting/_api/web/GetFolderByServerRelativeUrl(''Freigegebene Dokumente/asdf'')/Files/add' +
    '(overwrite=true,url=''' + fileName + '.' + fileMgmt.GetExtension(selectedFile) + ''')';
    jso.Add('body', base64Convert.ToBase64(instr));
    Client.DefaultRequestHeaders.Add('Authorization', 'Bearer ' + accessToken);
    HttpHeadersContent.Add('Content-Length', Format(StrLen(bodyText)));
    response.Headers.Add('accept', 'application/pdf');
    client.Post(uri, Content, response);

Result in SharePoint: Uploaded super simple textfile

Thank you in advance for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.