簡體   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