npm multer 文件上传 Express app 范本就不写了,仅记录一下上传部分的代码。 [url=][/url]
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; 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;};[url=][/url]
看到注释的那段读写文件的code了,其实multer已经把文件保存在multer_dest.dest的文件夹下面了,在同一个文件夹下,只需要rename就行了,不需要再读写了。
|