How to upload a file with axios request which can run both in the nodejs and browser env
I'm trying to write codes with javascripts to upload a file version with the endpoint:
It works well if I pass the File object in the formData for the file parameter.
But as the File type only exists in the browser, so I tried to use arraybuffer/buffer as the file value(I also don't want to use the fs.stream as it only works in the nodejs), but it seems the result is not correct after I have uploaded the content to the server(the file content is changed).
But if I set the content to be plain text, the upload result also works well.
So, my question is how to pass an arraybuffer/buffer/string as the content for a file?
The following are my codes:
let body = "";
const binary = this.ab2str(_fileBuffer);
body +=
"--" +
boundary +
'\r\nContent-Disposition: form-data; name="attributes"' +
"\r\n\r\n" +
`{"name": "${item.filename}"}` +
"\r\n" +
"--" +
boundary +
'\r\nContent-Disposition: form-data; name="file"; filename="' +
item.filename +
'"' +
"\r\nContent-type: application/octet-stream" +
"\r\n\r\n" +
binary +
"\r\n" +
"--" +
boundary +
"--\r\n";
try {
const response = await axios.post(
`${getUploadFileVersion(identifier)}`,
body,
{
headers: {
"Content-Type": `multipart/form-data; boundary=${boundary}`,
Authorization: `Bearer ${tokenInfo.accessToken}`
}
}
);
-
Hi ,
There are a few things to unpack on this one. We asked around the team, and while we have a number of axios samples, they don't show what you're looking for via a buffer. On this front we have an internal ticket filed to spend some time looking at this in the context of chunked uploads, which would provide that information. This is most likely a little ways out on the list but we're tracking it.
Here are a few things that might help you in what you're looking for:
- JavaScript SDK: This is part of our community projects and isn't directly maintained by Box, but it will give you a front-end JS solution that may provide the capabilities needed.
- Node SDK: Using in conjunction with the JavaScript SDK to provide the server-side capabilities for communicating with Box.
- Jon
サインインしてコメントを残してください。
コメント
2件のコメント