Express multer 文件上传
程序员文章站
2022-05-18 20:10:16
npm multer 文件上传 Express app 范本就不写了,仅记录一下上传部分的代码。 const fs = require('fs'); const express = require('express'); const multer = require('multer'); const ......
npm multer 文件上传
express app 范本就不写了,仅记录一下上传部分的代码。
const fs = require('fs'); const express = require('express'); const multer = require('multer'); const multer_dest = multer({dest: 'public/uploads/'}); const async_route_wrap = fn => { return function wrap(...args) { const ret = fn(...args); const next = args[args.length - 1]; return promise.resolve(ret).catch(next); }; }; const index = async(req, res) => { res.send(`<form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="file1"/> <button type="submit">upload</button> </form`); }; const upload = async(req, res) => { if (!req.files) return res.json({status: 'failed.'}); const count = req.files.length; for (let i = 0; i < count; i++) { const {originalname, size, path: upload_path} = req.files[i]; const save_path = `./public/uploads/${originalname}`; console.log(`name: ${originalname}, size: ${size}`); fs.renamesync(upload_path, save_path); /* fs.readfile(file_path, (err, data) => { fs.writefile(new_path, data, (err) => { if (err) { console.error(err); throw err; } else { if (i + 1 === count) { res.json({status: 'success'}); } } }); }); */ } res.json({ status: 'success' }); }; module.exports = () => { const router = express.router(); router.get('/', async_route_wrap(index)); router.post('/upload', multer_dest.any(), async_route_wrap(upload)); return router; };
看到注释的那段读写文件的code了,其实multer已经把文件保存在multer_dest.dest的文件夹下面了,在同一个文件夹下,只需要rename就行了,不需要再读写了。