Node.js express使用Multer实现文件上传
html部分
<div>
<h3>文件上传:</h3>
选择一个文件上传: <br/>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="content"/>
<br/>
<input type="submit" value="上传文件"/>
</form>
</div>
Node.js部分
安装multer:npm install multer --save
var express = require(‘express‘);
var app = express();
var fs = require(‘fs‘);
var multer = require(‘multer‘);
var upload = multer({dest: ‘uploadFile/‘});
//文件上传
app.post(‘/upload‘, upload.any(), function (req, res, next) {
console.log(req.files[0]); // 上传的文件信息
var newFile = "./uploadFile/" + req.files[0].originalname;
fs.readFile(req.files[0].path, function (err, data) {
fs.writeFile(newFile, data, function (err) {
if (err) {
console.log("错误:", err)
} else {
let response = {
message: ‘上传成功‘,
filename: req.files[0].originalname
};
res.json(response);
}
});
})
})
//图片加载,存储在uploadFile下的所有图片
app.get(‘/uploadFile/*‘, function (req, res) {
res.sendFile( __dirname + "/" + req.url );
})
github地址:https://github.com/Rossy11/no...
来源:https://segmentfault.com/a/1190000017169395
原文地址:https://www.cnblogs.com/thatme/p/10162277.html
时间: 2024-11-05 13:49:42