【发布时间】:2020-07-02 11:25:03
【问题描述】:
我正在尝试让我的 node.js 后端将文件上传到 AWS S3,它是在我的前端的发布请求中获得的。这是我的函数的样子:
async function uploadFile(file){
var uploadParams = {Bucket: '<bucket-name>', Key: file.name, Body: file};
s3.upload (uploadParams, function (err, data) {
if (err) {
console.log("Error", err);
} if (data) {
console.log("Upload Success", data.Location);
}
});
}
当我尝试以这种方式上传文件时,出现 Unsupported Body Payload 错误...
我过去使用 fileStream.createReadStream() 上传文件保存在服务器上的目录中,但是创建 fileStream 对我不起作用,因为这里没有要传递的路径参数。
编辑: 文件对象是在我的 Web 应用程序的 Angular 前端中创建的。这是用户上传文件的相关html代码:
<div class="form-group">
<label for="file">Choose File</label>
<input type="file" id="file"(change)="handleFileInput($event.target.files)">
</div>
如果事件发生,则调用对应组件中的handleFileInput(files: FileList)方法:
handleFileInput(files: FileList) {
// should result in array in case multiple files are uploaded
this.fileToUpload = files.item(0);
// actually upload the file
this.uploadFileToActivity();
// used to check whether we really received the file
console.log(this.fileToUpload);
console.log(typeof this.fileToUpload)
}
uploadFileToActivity() {
this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
// do something, if upload success
}, error => {
console.log(error);
});
}
文件上传服务的postFile(fileToUpload: File)方法用于发出post请求:
postFile(fileToUpload: File): Observable<Boolean> {
console.log(fileToUpload.name);
const endpoint = '/api/fileupload/single';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
return this.httpClient
.post(endpoint, formData/*, { headers: yourHeadersConfig }*/)
.pipe(
map(() => { return true; }),
catchError((e) => this.handleError(e)),
);
}
这是接收文件然后调用uploadFile(file)函数的服务器端代码:
app.post('/api/fileupload/single', async (req, res) => {
try {
if(!req.files) {
res.send({
status: false,
message: 'No file uploaded'
});
} else {
let file = req.files.fileKey;
uploadFile(file);
//send response
res.send({
status: true,
message: 'File is uploaded',
data: {
name: file.name,
mimetype: file.mimetype,
size: file.size
}
});
}
} catch (err) {
res.status(500).send(err);
}
});
非常感谢您帮助解决这个问题!
最好的问候,塞缪尔
【问题讨论】:
-
Body 需要是 Buffer、Typed Array、Blob、String 或 ReadableStream。它是什么类型的?
-
@jarmod 当我使用
typeof记录数据类型时,我得到了日志:object。如果重要的话,我最初上传的文件是 .pdf。我尝试使用:Buffer.from(JSON.stringify(file), 'utf-8')将文件转换为 Buffer 类型,但这对我不起作用。感谢您的帮助! -
您是如何创建
file对象的?你能添加那个代码吗? -
@jarmod 感谢您的快速回复。我编辑了我的问题并包含了代码。最好的问候!
-
您已经展示了客户端代码,但服务器端代码才是关键。接收发布文件的代码,然后将每个文件提供给您的“上传到 S3”函数。你在服务器端做什么来接受上传的文件?例如,您可能拥有将其保存到磁盘的中间件,或者您可能正在使用 Express 以特定格式将文件内容传递给您。
标签: javascript node.js amazon-web-services amazon-s3 backend