typora-copy-images-to: images
typora-root-url: ./
自定义存储文件名称
自定义路径
安装 express
1.应用生成器工具 express-generator 可以快速创建一个应用的骨架。
$ npm install express-generator -g
? $ express --no-view myapp
(此处创建不带模板引擎)
? 2. 部署自动化刷新
npm install --save-dev nodemon
修改 package.json 的 scripts 内容:
"scripts": {
"start": "node ./bin/www",
"dev": "nodemon ./bin/www"
}
之后,使用
npm run dev
运行
修改默认模板
<html>
<head>
<title>Express</title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<input type="file" class="file" name=‘file‘>
<a href="javascript:;" class="submit">提交</a>
</body>
<script>
document.querySelector(‘.submit‘).addEventListener(‘click‘,function(){
const files = document.querySelector(‘.file‘).files[0];
console.log(files)
let formdata = new FormData();
formdata.append(‘file‘, files);
fetch(‘/users/add‘,{
method:‘POST‘,
body:formdata
}).then((res)=>{
console.log(res)
}).catch((err)=>{
console.log(err)
})
})
</script>
</html>
安装中间件multer
cnpm install multer --save-dev
接口部署到user.js文件内
接口访问/users/add
user.js文件
var express = require(‘express‘);
var router = express.Router();
const multer = require(‘multer‘);/* 图片上传 */
const path=require("path");
/* GET users listing. */
router.get(‘/‘, function(req, res, next) {
res.send(‘respond with a resource‘);
});
router.post(‘/add‘, uploadFile, function (req, res, next) {
let src = req.body.file;
res.json({‘state‘:‘success‘, ‘result‘: src });
});
//自定义中间件
function uploadFile(req,res,next){
//dest 值为文件存储的路径;single方法,表示上传单个文件,参数为表单数据对应的key
// let upload = multer({ dest: "public/uploads" }).single("photo");
//设置文件的名称
let filename = "";
//获取绝对路径
let fullPath = path.resolve(__dirname,"../public/uploads");
console.log(fullPath)
let storage = multer.diskStorage({
//设置存储路径
destination:(req,file,cb)=>{
console.log("destination:",file);
// cb(null,fullPath);
cb(null,‘public/uploads‘);
},
//设置存储的文件名
filename:(req,file,cb)=>{
console.log("filename:",file);
//获取文件的扩展名
let extname=path.extname(file.originalname);
filename=file.fieldname+"-"+Date.now()+extname;
cb(null,filename);
}
})
let upload = multer({ storage: storage }).single("file");
/* single属性名需和上传的name一致否则报错:multererr:MulterError: */
upload(req,res,(err)=>{
console.log(req.file);
/* 文件存入 */
if (err instanceof multer.MulterError) {
res.send("multererr:" + err);
console.log("multererr:" + err);
return false;
}else if(err){
res.send("err:" + err);
return false;
}else{
//上传成功后,将图片写在req.body.photo中,继续住下执行
// req.body.photo=filename;
req.body.photo = req.file;
console.log({ ‘filesuccess‘: req.file })
next();
}
})
}
module.exports = router;
node express 使用中间件multer实现文件上传
原文:https://www.cnblogs.com/NB-JDzhou/p/13778341.html