javascript - 无法成功上传图片到s3然后查看
问题描述
我正在尝试将图像作为应用程序的一部分上传到 s3 存储桶。
index.js
function upImg(req) {
if(req.files.img) {
var img = req.files.image;
var name = Math.round(Math.random()*10000).toString(); // Returns a random 5 digit number
if(myDB.uploadImg(img, name)) {
return name;
} else {
return "";
}
} else {
return "";
}
}
app.post('/newEV*', isLoggedIn, function(req, res) {
var myURL = req.path.replace('/newEV', '');
var imgPath = upImg(req);
fetch(myURL).then(function (events){
var myID;
var x = 0;
while(!myID) {
if(!events[x]) {
myID = x;
} else {
x++;
}
}
myDB.newEvent(myURL, req.body.name, req.body.desc, req.body.loc, imgPath, req.body.link, req.body.cap, req.body.date, req.body.time, myID, events);
res.redirect('/edit' + myURL);
});
});
我的数据库文件
function signs3(file, name) {
devs3();
const s3 = new aws.S3();
const s3Params = {
Body: file,
Bucket: S3_BUCKET,
Key: name
};
s3.putObject(s3Params, function(err, data) {
if(err) {
throw err;
} else {
console.log("Data from putObject:" + JSON.stringify(data));
}
});
}
module.exports = {
uploadImg : function(file, name) {
var nName = "imgs/" + name;
console.log(nName);
signs3(file, nName);
return true;
}
}
我知道signs3 函数可以工作,因为我可以在我的应用程序的其他部分中使用它来上传JSON 文件。每当我发布到 URL 时,奇怪的是我可以在控制台中看到“来自 putObject 的数据”,但是我看不到的是 nName。我不明白这一点,因为该console.log(nName)
行应该在另一行之前运行。当我去查看存储桶时,图像尚未上传(尽管我从控制台获取了一个 ETag),并且页面没有显示在那里(我知道这也有效,因为它可以显示已经上传到存储桶的图像)。
解决方案
您想做这样的事情,从调用putObject时创建的Request 对象请求事件。
const req = s3.putObject( s3Params )
req.on('success', res => {
console.log ('upload complete! );
});
req.on ('error', res => {
console.error (res.error');
});
req.send();
为什么这对于小文件(JSON 文件)和大文件(图像)的工作方式似乎不同?因为大文件需要更长的时间来上传。
推荐阅读
- node.js - 如何从 React 一起传递图像和 JSON 并从 Nodejs 中的 req.body 获取?
- google-apps-script - 在 Google Apps 脚本中更改图表边框颜色
- javascript - 运行 Vue 项目时获取 net::ERR_CONTENT_LENGTH_MISMATCH 200 (OK)
- python - 尽管能够从同一模块导入不同的类,但无法在导入的模块中找到类
- node.js - 使用 express 和头盔服务的 React 应用程序无法发出 API 请求
- python-3.x - 需要帮助来理解这个枚举函数
- c# - 具有不可避免的异步等待调用的 ValueTask 方法?
- ios - 在 Swift / SwiftUI 中将变量对象从视图传递到可观察对象
- sql - 存储过程,返回不同的列数
- postgresql - 派生过程时插入字符串值