我设置了一个服务器来运行二十一点游戏,我想使用后端的multer将个人资料图片存储在亚马逊S3上.但是,每当我尝试将图像从前端发送到后端时,我的req.file都是未定义的.
有很多关于该探针的帖子,但是我已经完成了他们所说的大部分内容,但无济于事.
我的HTML输入:
<fieldset>
<legend>Create Account</legend>
Username:<input type="text" id="createUser"><br>
Password:<input type="password" id="createPW"><br>
Screen Name: <input type="text" id="createScreen"><br>
Profile Picture: <input type="file" enctype="multipart/form-data" id="avatar" name="avatar" accept="image/png, image/jpeg">
<button id="createAccountButton">Submit</button>
</fieldset>
我的前端提取(纯js):
fetch(ec2+"/image-upload", {method: "POST", body: file}).then(checkStatus).catch(function(e){console.log(e);});
我的后端:
server.js
const singleUpload = upload.single('avatar');
app.post('/image-upload',function(req, res) {
console.log(req.file);
singleUpload(req, res, function(err, some) {
if (err) {
return res.status(422).send({errors: [{title: 'Image Upload Error', detail: err.message}] });
}
return res.json({'imageUrl': req.file.location});
});
})
上载:
var upload = multer({
storage: multerS3({
s3: s3,
bucket: 'cloud-bj-bucket',
acl: 'public-read',
metadata: function (req, file, cb) {
cb(null, {fieldName: 'TESTING_METADATA'});
},
key: function (req, file, cb) {
cb(null, file.filename);
}
})
})
错误在后端部分内
编辑:
这是我如何从html获取图像
var file = document.getElementById("avatar").files[0];
fetch(ec2+"/image-upload", {method: "POST", body: file}).then(checkStatus).catch(function(e){console.log(e);});
解决方法:
这是因为您试图在执行upload.single之前访问req.file.像这样简单地链接中间件:
const singleUpload = upload.single('avatar');
app.post('/image-upload', singleUpload, function(req, res) { // <-- mount it here
console.log(req.file)
// rest of the code
}
您可以使用FormData设置正确的标头,然后在提取调用中使用它.但是,您将需要一个表单元素.
var file = document.getElementsByTagName("form");
var data = new FormData(file)
fetch(ec2+"/image-upload", {
method: "POST",
body: data
})
最简单的选择是拥有form元素并直接调用api,而不会涉及获取:
<form action="/image-upload" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>Create Account</legend>
Username:<input type="text" id="createUser">
Password:<input type="password" id="createPW">
Screen Name: <input type="text" id="createScreen">
Profile Picture: <input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg">
<button type="submit" id="createAccountButton">Submit</button>
</fieldset>
</form>