microsoft-dynamicsdynamics-business-centralmicrosoft365

Business Central API V2 Uploaded Attachment is empty


I create attachments for Business Central, Journal Lines, using the V2 API. The code looks like this:

// Creating a file

const fileData = new FormData()
const fileBlob = new Blob([file.buffer], { type: 'application/pdf' })
fileData.append('file', fileBlob, `${file.name}.pdf`)

// Creating a line

const { data } = await firstValueFrom(
    this.businessCentralHttpService.post<JournalLineModel>(
        `companies(${bcCompanyId})/journals(${journalId})/journalLines`,
        dataToSend, // does not matter - everything works here
    ),
)

// Creating an attachment - also works

const { data: attachment } = await firstValueFrom(
  this.businessCentralHttpService.post<{
    id: string
    parentId: string
  }>(`companies(${bcCompanyId})/attachments`, {
    parentId: data.id,
    fileName: `${file.name}.pdf`,
    parentType: 'Journal',
  }),
)

// This seems to always leave the attachment empty

const response = await firstValueFrom(
  this.businessCentralHttpService.patch(
    `companies(${bcCompanyId})/attachments(${attachment.id})/attachmentContent`,
    fileData,
    {
      headers: {
        'If-Match': '*',
        'Content-Type': 'multipart/form-data',
      },
    },
  ),
)

The API Documentation I'm using doesn't mention anything about formdata, but neither it does show an example of how the content needs to be uploaded.

The request for updating the content doesn't fail, returns 204, but the file seems corrupt (empty).


Solution

  • As we discussed, it seemed that the header ‘Content-Type’: ‘multipart/form-data’ was being ignored for some reason.

    A quick rewrite of the code to standard node with fetch solved the problem.

    Apparently axios (which is used by HttpService) doesn't work properly with ‘Content-Type’: ‘multipart/form-data’ or perhaps wasn't used as intended. I haven't looked into it further, as the problem was solved by a rewrite.