1.form表单上传
<form>
<input type="file" @change="getFile($event)">
<button @click="submit($event)">上传</button>
</form>
2.methods方法
getFile(event) {
this.file = event.target.files[0];
console.log(this.file);
},
submit(event) {
event.preventDefault();
let formData = new FormData();//创建form对象
formData.append('file', this.file);//通过append向form对象添加数据
let config = {
headers: {
'Content-Type': 'multipart/form-data'//添加请求头
}
}
this.axios.post('与后端约定好的url', formData, config).then(function (response) {
if (response.status === 200) {
console.log(response.data);
}
})
}
3.node.js添加路由
//下面三个分别是处理文件上传、文件操作和路径管理的模块
//multer需要安装其他两个node自带
let multer = require('multer');
let fs = require('fs');
let path=require('path');//配置接受来的文件存放路径
let upload = multer({dest: 'uploads/'});
router.post('/up', upload.single('file'), (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET,POST");
//此处为重写文件名为原文件名,因为上传以后文件名为乱码
fs.renameSync(req.file.path,`uploads/${req.file.originalname}`);
res.json({
success: '成功',
file: req.file
});
});
下载文件
//下载文件
router.get('/down', (req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET,POST");
//此处为判断url是否存在,存在执行否则返回错误
//前端传参:url=文件名
req.query.url ? res.download(`uploads/${req.query.url}`) : res.json({
message: '失败'
});
});