以前我通过 post 将我的 Javascript 对象发送到节点后端。工作正常。问题是我必须移动以形成数据,因为我将 json 中的头像更改为 s3 url 而不是 base64。所以我安装了multer和multer-s3。我无法上传头像或更新其他 Javascript 对象属性。
我的 Javascript 对象的结构与
{
info: {
name: 'abc',
avatar: Blob Instance
},
address: {},
education: {}
}
我的多路代码是
const multer = require('multer');
const aws = require('aws-sdk');
const BUCKET_NAME = 'myBucket';
var multerS3 = require('multer-s3');
aws.config.accessKeyId = 'someId';
aws.config.secretAccessKey = 'someKey';
aws.config.region = 'us-east-2';
var upload = multer({
storage: multerS3({
s3: new aws.S3(),
bucket: BUCKET_NAME,
acl: 'public-read',
contentType: multerS3.AUTO_CONTENT_TYPE,
metadata: function(req, file, cb) {
console.log(file);
cb(null, { fieldName: file.fieldname });
},
key: function(req, file, cb) {
let id = req.user._id;
cb(null, id + '/' + Date.now().toString() + '_' + file.originalname);
},
}),
});
我的路线是
router.post(
'/',
authorizeUser,
upload.single('avatar'),
controller.updateWithAsscociations
);
在我的控制器 func updateWithAsscociations 中,我什么也没得到。logoURL 和其余的都不是
看起来您只需要稍微更改请求结构并将头像图像表单字段与文本字段一起发送。就像是:
curl --request POST 'http://localhost:3000/test-upload' \
--form 'info[name]="someName"' \
--form 'address[street]="someStreet"' \
--form 'address[number]="123"' \
--form 'avatar=@"/path/to/your/image"'
下面是如何访问 nodejs 端的数据:
const multer = require('multer');
const upload = multer({dest: 'uploads/'})
app.post('/test-upload', upload.single('avatar'), (req, res, next) => {
// req.file is the `avatar` file
// req.body will hold the text fields (converted to an object)
console.log("avatar file is", req.file);
console.log("body is", JSON.stringify(req.body));
res.status(201).end();
})
因此,当执行“测试上传”请求时,控制台会记录以下内容:
avatar file is {
fieldname: 'avatar',
originalname: '<name-of-file>',
...
destination: 'uploads/',
path: 'uploads\\2d907155c413320252e8fce04c266840',
size: 477
}
body is {"info":{"name":"someName"},"address":{"street":"someStreet","number":"123"}}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句