AWS S3上传0 B文件- node.js

ep6jt1vc  于 11个月前  发布在  Node.js
关注(0)|答案(2)|浏览(111)

我尝试使用[putObject][1]将文件上传到AWS S3,但结果文件大小为0字节。
我确实从putObject调用中得到了成功的响应。

Node.js代码:

const aws = require("aws-sdk");
const s3 = new aws.S3();

module.exports = {
  upload: function(req, res, next) {
    console.log("Going to upload");
    console.log(req.files);
    let uploadFile = req.files.file;
    const s3PutParams = {
      Bucket: process.env.S3_BUCKET_NAME,
      Key: uploadFile.name,
      Body: uploadFile.data,
      ACL: "public-read"
    };

    const s3GetParams = {
      Bucket: process.env.S3_BUCKET_NAME,
      Key: uploadFile.name
    };

    console.log(s3PutParams);
    s3.putObject(s3PutParams, function(err, response) {
      if (err) {
        console.error(err);
      } else {
        console.log("Response is", response);
        var url = s3.getSignedUrl("getObject", s3GetParams);
        console.log("The URL is", url);
        res.json({
          returnedUrl: url,
          publicUrl: `https://${process.env.S3_BUCKET_NAME}.s3.amazonaws.com/${uploadFile.name}`
        });
      }
    });
  }
};

字符串

**通过POSTMAN测试:**x1c 0d1x
后端控制台日志

有谁能帮我找出什么是错的吗?

  • 11/20编辑:* @EmmanuelNK帮助发现了Buffer.byteLength(req.files.file.data)为0的事实。他有以下问题:

你是想把整个缓冲区写入内存还是想把它流到s3?
对不起,如果答案不是重点,仍然让我的脚湿。基本上我想上传一个图像到S3,然后稍后使用该URL在网页上显示它。换句话说,就像一个photobucket
如何使用Upload
现在我只是测试我的后端代码(张贴在问题)使用 Postman 。一旦我得到了去,将有一个文件上传形式的前端调用此路由。
有帮助吗?提前感谢你的帮助。

9nvpjoqh

9nvpjoqh1#

如果您使用express-fileupload作为文件上传中间件,并且您已将useTempFiles选项设置为true,请记住,您的数据文件缓冲区将为空(检查使用情况),这与您面临的问题相关。要解决此问题,只需再次读取temp. file以获得预期的文件缓冲区。

import fs from 'fs';
// OR
const fs = require('fs');

// in your route
let uploadFile = req.files.file;
// THIS
fs.readFile(uploadedFile.tempFilePath, (err, uploadedData) => {
    if (err) { throw err; }

    const s3PutParams = {
        Bucket: process.env.S3_BUCKET_NAME,
        Key: uploadFile.name,
        Body: uploadData, // <--- THIS
        ACL: "public-read"
    };

    const s3GetParams = {
        Bucket: process.env.S3_BUCKET_NAME,
        Key: uploadFile.name
    };

    console.log(s3PutParams);
    s3.putObject(s3PutParams, function(err, response) {
        if (err) {
            console.error(err);
            throw err;
        } else {
            console.log("Response is", response);
            var url = s3.getSignedUrl("getObject", s3GetParams);
            console.log("The URL is", url);
            res.json({
                returnedUrl: url,
                publicUrl: `https://${process.env.S3_BUCKET_NAME}.s3.amazonaws.com/${uploadFile.name}`
            });
        }
    });
});

字符串

llycmphe

llycmphe2#

我知道这可能是旧的,但我只是有这个问题。如果你要直接上传到S3,设置温度为假。

app.use(fileUpload({
  useTempFiles : false,
  tempFileDir : '/tmp/',
  debug:true
}));

字符串

相关问题