我正在尝试将文件上传到S3。我的UI支持拖放和文件输入元素,因此我的计划是从drop和输入事件返回的blob开始,使用FileReader加载其内容,然后使用FormData进行处理。 / p>
问题出在*****
。看起来好像.result
是一个非零大小的数组缓冲区,但我在S3上找到的只是一个名为${filename}
的内容为[object ArrayBuffer]
的20b文件。
我在此流程中缺少什么
function sendSigned(fileObj, cb) {
console.log("send signed", fileObj)
let formData = new FormData();
const host = "http://localhost:4000"
formData.append("key", fileObj.signature.stem + "${filename}");
formData.append("x-amz-algorithm", "AWS4-HMAC-SHA256");
formData.append("x-amz-credential", fileObj.signature.credential);
formData.append("x-amz-date", fileObj.signature.date);
formData.append("success_action_redirect", host + "/upload/success");
formData.append("policy", fileObj.signature.policy);
formData.append("x-amz-signature", fileObj.signature.signature);
let fileReader = new FileReader();
fileReader.onload = function(evt) {
console.log(evt);
// ******************************************
// formData.append("file", evt.target.result);
formData.append("file", fileReader.result);
jQuery.ajax({
url: 'http:\/\/uploads.s3.amazonaws.com',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: (res) => {
console.log(res);
let s3Conf = Object.assign(fileObj, {
confirmation: res.ETag,
zipname : fileObj.signature.stem + fileObj.nativeFiles[0].name,
status: "Done"
});
cb(s3Conf);
},
error: (err) => {
console.error(err);
let s3Conf = Object.assign(fileObj, {
error: err,
status: "Done"
});
cb(s3Conf);
}
});
}
fileReader.readAsArrayBuffer(fileObj.nativeFiles[0].blob);
}
答案 0 :(得分:2)
您无法使用FormData对象发送数组缓冲区(但您可以将其作为整个帖子正文发送)。 FormData接受blob,因此您可以将其传递给它。
function sendSigned(fileObj, cb) {
console.log("send signed", fileObj)
let formData = new FormData();
const host = "http://localhost:4000"
formData.append("key", fileObj.signature.stem + "${filename}");
formData.append("x-amz-algorithm", "AWS4-HMAC-SHA256");
formData.append("x-amz-credential", fileObj.signature.credential);
formData.append("x-amz-date", fileObj.signature.date);
formData.append("success_action_redirect", host + "/upload/success");
formData.append("policy", fileObj.signature.policy);
formData.append("x-amz-signature", fileObj.signature.signature);
formData.append("file", fileObj.nativeFiles[0].blob, fileObj.nativeFiles[0].name);
jQuery.ajax({
url: 'http:\/\/uploads.s3.amazonaws.com',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: (res) => {
console.log(res);
let s3Conf = Object.assign(fileObj, {
confirmation: res.ETag,
zipname : fileObj.signature.stem + fileObj.nativeFiles[0].name,
status: "Done"
});
cb(s3Conf);
},
error: (err) => {
console.error(err);
let s3Conf = Object.assign(fileObj, {
error: err,
status: "Done"
});
cb(s3Conf);
}
});
}
请注意,您的服务器端逻辑需要将字段名称作为文件字段读取。