繁体   English   中英

使用 Node.js 上传 AWS S3 文件:不支持的正文有效负载错误

[英]AWS S3 file upload with Node.js: Unsupported body payload error

我正在尝试让我的 node.js 后端将文件上传到 AWS S3,它是在我的前端的 post 请求中获得的。 这是我的函数的样子:

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 应用程序的角度前端中创建的。 这是用户上传文件的相关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);
    }
  });

非常感谢您帮助解决这个问题!

最好的问候,塞缪尔

最好的方法是流式传输文件。 假设你是。 从磁盘读取它。 你可以这样做

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM