定义一个upload.js文件用来处理上传的路由
- 此处上传需要一个中间件multer,使用的时候需要在安装
- 代码如下
// upload.js
const express = require('express')
const router = express.Router()
const fs = require('fs')
const multer = require('multer')
// 设置临时文件存放文件夹
const upload = multer({dest: 'upload_tmp/'});
router.post('/', upload.any(), function(req, res, next) {
// 设置文件的存放地址
var des_file = "./upload/" + req.files[0].originalname;
fs.readFile( req.files[0].path, function (err, data) {
fs.writeFile(des_file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files[0].originalname
};
res.end( JSON.stringify( response ) );
}
});
});
});
module.exports = router