我目前具有以下功能,可以将文件从表单上传到s3:
function uploadFileToS3(presignedPostData, file) {
var formData = new FormData();
Object.keys(presignedPostData.fields).forEach(function(key) {
formData.append(key, presignedPostData.fields[key]);
});
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", presignedPostData.url, true);
xhr.send(formData);
xhr.onload = function() {
console.log('uploaded')
};
}
presignedPostData基本上是s3中的一个对象,它提供正确的令牌以将文件上传到存储桶,并且该文件只是页面中<input />
的文件。
我正在尝试在Node JS中复制相同的功能。这是我到目前为止的内容:
const request = require('request').defaults({ encoding: null });
const FormData = require('form-data');
const fetch = require('node-fetch');
const url = 'https://www.a.com/some-file.csv';
const presignedPostData = {} // an object that contains the s3 tokens etc
const options = {
url
};
function callback(error, response, buffer) {
if (!error && response.statusCode == 200) {
uploadFileToS3(presignedPostData, buffer)
}
}
request(options, callback);
function uploadFileToS3(presignedPostData, buffer) {
const formData = new FormData();
Object.keys(presignedPostData.fields).forEach(function(key) {
if (presignedPostData.fields[key]) {
formData.append(key, presignedPostData.fields[key]);
}
});
formData.append('Content-Type', 'application/octet-stream')
formData.append('file', buffer);
fetch(presignedPostData.url, {
method: 'POST',
body: formData,
headers: formData.getHeaders()
})
.then(json => {
console.log(json)
})
.catch(e => console.log('there was an error'))
}
当我尝试将文件发布到s3时,收到状态400
错误。表单数据应该是相同的,但可能与我试图发送缓冲区而不是文件的事实有关。或Content-Type
标头不正确。
不确定我在这里哪里出错了吗?