在平时工作和自己写小项目时会遇到需要上传文件的场景,这里使用nodejs搭建服务端接口。
模块
const express = require('express');
const app = express();
const cors = require('cors');
const multer = require('multer');
const fs = require('fs');
- multer是用于处理文件上传的nodejs中间件,主要跟express框架搭配使用,只支持表单MIME编码为multipart/form-data类型的数据请求
- fs模块用于对系统文件及目录进行读写操作
- cors用来处理带cookie的跨域请求
接口
const express = require('express');
const app = express();
const cors = require('cors');
const fs = require('fs');
const multer = require('multer');
// 引入multer
const upload = multer({
dest: 'uploads/'
});
morgan.token('body', (req: { body: any; }) => {
return JSON.stringify(req.body);
});
// 托管静态文件,并且加个前缀uploads,为了安全规范
app.use('/uploads', express.static(__dirname + '/uploads'));
// 处理带cookies的跨域请求
app.use(cors({credentials: true, origin: 'http://localhost:8080'}));
// 接口填写,上传文件类型为任何文件
app.post('/upload', upload.any(), async (req: any, res: any) => {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
console.log(req.files[0]); // 上传的文件信息
// 保存文件,或者做一些后续文件的处理
var des_file = "./uploads/" + req.files[0].originalname;
fs.readFile( req.files[0].path, (err: any, data: any) => {
fs.writeFile(des_file, data, (err: any) => {
if(err){
console.log(err);
}else{
const response = {
message: 'File uploaded successfully',
filename: req.files[0].originalname
};
res.end(JSON.stringify(response));
}
});
});
})