Multer 文件上传不工作 multipart/form-data 图片
Multer file upload not working multipart/form-data image
我正在使用 nuxt.js。我使用了一个包 vue-picture-input and am using this 教程来上传图像文件。在我的 api:
上使用 axios 将其上传到服务器
export default function (url, file, name = 'avatar') {
if (typeof url !== 'string') {
throw new TypeError(`Expected a string, got ${typeof url}`);
}
// You can add checks to ensure the url is valid, if you wish
let formData = new FormData();
formData.append(name, file);
const config = {
headers: {
'content-type': 'multipart/form-data'
}
};
return axios.post(url, formData, config);
};
发送前我仔细检查过,formData确实有图像。此请求然后转到后端并由以下代码接收:
const storage = multer.diskStorage({
destination: 'some-destination',
filename: function (req, file, callback) {
crypto.pseudoRandomBytes(16, function(err, raw) {
if (err) return callback(err);
callback(null, raw.toString('hex') + path.extname(file.originalname));
});
}
});
var upload = multer({ storage : storage})
router.post('/upload/add', upload.single('avatar'), (req, res) => {
if (!req.file) {
console.log("No file received");
return res.send({
success: false
});
} else {
console.log('file received');
return res.send({
success: true
})
}
// Everything went fine
})
我知道我这样做的方式很奇怪 - 使用 formData 而不是实际提交 html 表单..但在我的场景中它更好。每当我 运行 这段代码时,响应总是 success: false
。
这是否意味着它找不到 formData 图像?如果您能帮助我调试它,我将不胜感激。干杯。
在研究类似问题时,我遇到了这个 post。我有这个以类似的方式工作。删除 content-type header 可能会有所帮助,它是由 axios/formdata 自动为我设置的。它应该包括像这样由 formdata 生成的边界。
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary5g0xJihuBbfw8DEp
我正在使用 nuxt.js。我使用了一个包 vue-picture-input and am using this 教程来上传图像文件。在我的 api:
上使用 axios 将其上传到服务器export default function (url, file, name = 'avatar') {
if (typeof url !== 'string') {
throw new TypeError(`Expected a string, got ${typeof url}`);
}
// You can add checks to ensure the url is valid, if you wish
let formData = new FormData();
formData.append(name, file);
const config = {
headers: {
'content-type': 'multipart/form-data'
}
};
return axios.post(url, formData, config);
};
发送前我仔细检查过,formData确实有图像。此请求然后转到后端并由以下代码接收:
const storage = multer.diskStorage({
destination: 'some-destination',
filename: function (req, file, callback) {
crypto.pseudoRandomBytes(16, function(err, raw) {
if (err) return callback(err);
callback(null, raw.toString('hex') + path.extname(file.originalname));
});
}
});
var upload = multer({ storage : storage})
router.post('/upload/add', upload.single('avatar'), (req, res) => {
if (!req.file) {
console.log("No file received");
return res.send({
success: false
});
} else {
console.log('file received');
return res.send({
success: true
})
}
// Everything went fine
})
我知道我这样做的方式很奇怪 - 使用 formData 而不是实际提交 html 表单..但在我的场景中它更好。每当我 运行 这段代码时,响应总是 success: false
。
这是否意味着它找不到 formData 图像?如果您能帮助我调试它,我将不胜感激。干杯。
在研究类似问题时,我遇到了这个 post。我有这个以类似的方式工作。删除 content-type header 可能会有所帮助,它是由 axios/formdata 自动为我设置的。它应该包括像这样由 formdata 生成的边界。
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary5g0xJihuBbfw8DEp