express文件上传组件:multer(express官方推荐使用,具体可以查看:https://github.com/expressjs/multer)
首先在express的app.js中:
var multer = require('multer');
var upload = multer({ dest: 'upload/' });
var app = express();
接口:
app.post('/file-upload-app',upload.single('logo'),function(req, res, next) {
var file = req.file;
console.log(file);
res.send({code: '上传成功'});
});
页面:
<form action="/file-upload-app" method="post" enctype="multipart/form-data">
<h2>单图上传</h2>
<input type="file" name="logo">
<input type="submit" value="提交">
</form>
注意红色字体必须保持一致,这是最基础的,具体功能查看官网api
如果是上传图片,可以将图片base64地址返回,代码如下修改file-upload-app接口:
var fs = require('fs');
router.post('/file-upload-app',upload.single('logo'),function(req, res, next) {
var file = req.file;
var filepath = file.path;
var base64Str = fs.readFileSync(filepath).toString('base64');//同步读取文件并且转换成base64
var datauri = 'data:image/png;base64,' + base64Str; //转换成 datauri 格式即可在网页上显示
res.send({code: '上传成功',url:datauri});
});