我正在尝试让我的 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)), ); }非常感谢您帮助解决这个问题!
1 回答
侃侃无极
TA贡献2051条经验 获得超10个赞
最好的方法是流式传输文件。假设你是。从磁盘读取它。你可以这样做
const fs = require("fs");
const aws = require("aws-sdk");
const s3Client = new aws.S3();
const Bucket = 'somebucket';
const stream = fs.createReadStream("file.pdf");
const Key = stream.path;
const response = await s3Client.upload({Bucket, Key, Body: stream}).promise();
console.log(response);
添加回答
举报
0/150
提交
取消