gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:52:06 24 4
gpt4 key购买 nike

我尝试使用 [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 测试: enter image description here

后端控制台日志 enter image description here

谁能帮我找出问题所在吗?

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

Are you trying to write the whole buffer into memory or are you trying to stream it to s3?

抱歉,如果答案不切题,我的脚仍然湿漉漉的。基本上我想将图像上传到 S3,然后使用该 URL 将其显示在网页上。换句话说就像一个照片桶

how you are using upload

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

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

最佳答案

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

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

关于node.js - AWS S3上传0B文件-node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58945867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com