目前,我正在使用Express 4.x进行一些项目,并且在该项目中似乎要处理文件上传(例如:在表单上上传图像)。我正在使用本地主机作为服务器(mysql),寻找线索的大多数人使用multer,但我无法获得。任何帮助,我感激
最佳答案
Formidable可帮助您解析并从POST请求中获取文件
示例代码:
const formidable = require('formidable');
const fs = require('fs');
const path = require('path');
// POST | /upload
app.post('/upload', (req, res) => {
const form = new formidable.IncomingForm();
form.parse(req, (error, fields, files) => {
if(error){
res.status(500);
console.log(error);
res.json({
error,
});
return false;
}
const image = files.image;
console.log(image.name) // pony.png
console.log(image.type) // image/png
// Get the tmp file path
const tmpFilePath = image.path; // /tmp/<randomstring>
// Rename and relocate the file
fs.rename(tmpFilePath, path.join(`${__dirname}/uploads/${image.name}`), error => {
if(error){
res.status(500);
console.log(error);
res.json({
error,
});
return false;
}
res.status(201);
res.json({
success: true,
upload_date: new Date(),
});
// Do all kinds of MySQL stuff lol
});
});
});
关于mysql - 在Express JS中使用mysql上传文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49249851/