繁体   English   中英

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

[英]AWS S3 uploading 0 B file - node.js

我正在尝试使用[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 进行测试: 在此处输入图像描述

后端控制台日志在此处输入图像描述

谁能帮我找出问题所在?

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

您是要尝试将整个缓冲区写入 memory 还是尝试将 stream 写入 s3?

对不起,如果答案不是重点,仍然让我的脚湿透。 基本上我想将图像上传到 S3,然后使用 URL 在网页上显示它。 换句话说,就像一个照片桶

您如何使用上传

现在我只是使用 postman 测试我的后端代码(发布在问题中)。 一旦我开始这样做,前端就会有一个文件上传表单调用这个路由。

这有帮助吗? 在此先感谢您的帮助。

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

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

暂无
暂无

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

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