需要使用 fastify-multer 将图像上传到 AWS S3 服务器得到 [Function: multerPreHandler] 错误

Need to upload image to AWS S3 server using fastify-multer getting [Function: multerPreHandler] error

  1. 使用的包
const fastify = require('fastify');
        const multer = require('fastify-multer');
        const server = fastify();
        server.register(multer.contentParser);
        var AWS = require("aws-sdk");
        var s3 = new AWS.S3();
        var storage = multer.memoryStorage();
        var upload = multer({ storage: storage }); 

inspired by Rohan Paul
2. 上传文件到AWS S3 bucket的功能

   uploadInvoice = async (req, res) => {
             var files = upload.single("file");
             try {
             
             const s3FileURL = ' https://up.s3.amazonaws.com/';
         
             let s3bucket = new AWS.S3({
                 secretAccessKey: "",
                 accessKeyId: "",
                 region: ""
             });
         
             const params = {
                 Bucket: '',
                 Body: files.buffer,
                 ContentType: files.mimetype,
                 ACL: "public-read",
                 key: files.originalname
             };
            
             s3bucket.upload(params, function (err, files) {
                 if (err) {
                     res.status(500).json({ error: true, Message: err });
                 } else {
                     res.send({ files });
                     var newFileUploaded = {
                         description: req.body.description,
                         fileLink: s3FileURL + files.originalname,
                         s3_key: params.Key
                     };
                     var document = new DOCUMENT(newFileUploaded);
                     document.save(function (error, newFile) {
                         if (error) {
                             throw error;
                         }
                     });
                 }
             });
         };

我得到的错误是 HttpErrorResponse {headers: HttpHeaders, status: 500, statusText: "Internal Server Error", url: "http://localhost:3000/v1/upload/files", ok: false, …} 错误:{statusCode: 500,错误:“内部服务器错误”,消息:“需要 params.Body”} headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} 消息:“http://localhost:3000/v1/upload/files 的 Http 失败响应:500 内部服务器错误” 名称:“HttpErrorResponse” 好的:假的 状态:500 statusText: "内部服务器错误" url: "http://localhost:3000/v1/upload/files" 原型:HttpResponseBase

在您的参数中,“键”是小写的,而上传时您使用的是 params.Key,应该是 params.key

如果您正在使用 fastify,请选择 fs 和 pump,而不是 multer,因为截至目前 fastify-multer 无法完全使用 AWS S3 上传

或许您可以尝试使用 multer-s3。它也应该与 fastify-multer.

一起使用

检查 link 到 multer-s3 以获取更多参考和示例:

https://github.com/anacronw/multer-s3