我有一个这样的对象数组:
data: [
{"image": File, "certificate": File},
{"image": File, "certificate": File}
]
我在服务器上读取文件的方式是在发送 POST 请求之前执行一个循环:
...
const fd = new FormData();
fd.append('image', data[0].image);
fd.append('image', data[1].image);
fd.append('certificate', data[0].certificate);
fd.append('certificate', data[1].certificate);
this.http.post('http://localhost:3000/upload', fd, options);
然后在服务器端我做:
upload.fields([{ name: 'image', maxCount: 2 }, { name: 'certificate', maxCount: 2 }])
所以我的问题是...有没有一种方法可以让我像这样发送数组:
fd.append('data', data)
所以 multer 可以获取数据字段中的文件?
最佳答案
对于任何仍在为此苦苦挣扎的人,这对我来说是有用的
后端代码:
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, './images/'))
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + file.originalname)
}
});
const upload = multer({ storage: storage })
app.post('/generate', upload.fields([{ name: 'layer1', maxCount: 6 }, { name: 'layer2', maxCount: 6 }, { name: 'layer3', maxCount: 6 }]), function (req, res) {
console.log(req.files)
})
客户请求:
const formdata = new FormData();
var myHeaders = new Headers();
myHeaders.append("Accept", "application/json");
for (const layer of layers) {
for (const img of layer.files)
formdata.append(`layer${layer.id}`, img)
}
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch("http://localhost:5000/generate", requestOptions)
https://stackoverflow.com/questions/58878043/
相关文章:
apache-spark - Spark : save ordered data to parque
java - Canny 边缘检测不检测 100% 水平/未旋转的线
amazon-web-services - 您应该使用客户端凭据授权类型来验证服务器到服务器吗?
node.js - 使用 fetch API 时如何记录实际的请求 header
google-cloud-platform - 使用 --allow-unauthenticated
apache-zookeeper - Chubby Sequencer 的目的是什么
mysql - 在 macOS Catalina 10.15.1 下安装 DBD::mysql 时遇
node.js - Angular 8 - GET styles.js net::ERR_CONTE