Joe
Joe

Reputation: 4234

Posting a multipart form with file in Axios, Nodejs

const form_data = new FormData();
form_data.append("File", fs.createReadStream(pathToFile));
form_data.append('Login', alias.toUpperCase());

const request_config = {
    headers: {
        "Authorization": "Basic 123",
        "Content-Type": 'multipart/form-data'
    },
    data: form_data
};

await axios.post(url, params, request_config).then(response => {

Posting to an endpoint I can't debug. The response is a 500.

This is the error:

enter image description here

Is this the correct way do it?

Can I somehow see exactly what Axios is sending?

This is a postman request I received from the author of the API. This passes:

POST /api/upload HTTP/1.1

Host: api.test.contoso.se

Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

Authorization: Basic 123

User-Agent: PostmanRuntime/7.13.0

Accept: */*

Cache-Control: no-cache

Postman-Token: 089af753-fa12-46c4-326f-dfc39c36faab,c5977145-ece3-4b53-93ff-057788eb0dcf

Host: api.test.contoso.se

accept-encoding: gzip, deflate

content-length: 18354

Connection: keep-alive

cache-control: no-cache

Content-Disposition: form-data; name="Lang"

SV
------WebKitFormBoundary7MA4YWxkTrZu0gW--

Content-Disposition: form-data; name="File"; filename="/C:/Users/file.docx


------WebKitFormBoundary7MA4YWxkTrZu0gW--

Content-Disposition: form-data; name="Login"

ABC

Upvotes: 0

Views: 10985

Answers (1)

shaochuancs
shaochuancs

Reputation: 16226

The error message in your screenshot is clear: "Missing content-type boundary".

To use axios for multipart/form-data request, you need to set boundary to upload the file. Example code is:

const form_data = new FormData();

...

const request_config = {
    headers: {
        "Authorization": "Basic 123",
        "Content-Type": 'multipart/form-data; boundary=' + form._boundary
    },
    data: form_data
};

await axios.post(...)

"Can I somehow see exactly what Axios is sending?"

You can use HTTP proxy software such as Charles to intercept the request, and check what data is sent.

Upvotes: 7

Related Questions