需求背景
node+express可以快速搭好一些后端接口,但是express默认没有处理请求体数据的相关方法,所以在解析处理post请求中的data数据时,需要配置一个express的中间件:body-parser。而像图片这种特殊的文件数据,后端要接收处理的话就需要用到另一个中间件:multer。
期望效果
前端点击上传图片后,便会将图片保存到后端配置好的静态资源文件夹中,然后返回该图片的静态资源链接。
后端代码实现
const express=require("express")
const mongoose = require('mongoose')
const router=express.Router()
const multer = require('multer')
const fs = require("fs")
const path=require('path')
const bodyParser=require('body-parser')
const app=express()
//跨域配置
app.all("*", function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "content-type")
res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS")
if (req.method.toLowerCase() == 'options')
res.send(200)
else
next()
});
//配置multer
var objMulter = multer({dest: './www/upload/'})
app.use(objMulter.any())
//将www这个文件夹作为静态资源进行开放
app.use('/www/',express.static(path.join(__dirname,'./www/')))
//配置body-parser中间件
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json());
//处理上传请求
router.post('/image/test',(req,res)=>{
var newName = req.files[0].path+path.parse(req.files[0].originalname).ext
fs.rename(req.files[0].path, newName, function(err){
if(err){
res.send('失败')
}else{
//返回该图片的静态资源路径
res.send('http://localhost:3000/www/upload/'+newName.slice(11))
}
})
})
app.listen(3000,()=>{
console.log("server is running")
})
前端代码实现
<template>
<div class="container-upload" >
//上传图片表单
<form action="">
<input ref="myinput" type="file">
<button @click.prevent="uploadForm">点击上传</button>
</form>
</div>
</template>
<script>
import axios from "axios";
export default {
data(){
return{
formData:''
}
},
methods:{
uploadForm(){
this.formData=new FormData() //文件类型的数据必须用FormData类型来进行传输
this.formData.append('file',this.$refs.myinput.files[0])
this.uploadImage(this.formData).then(res=>{
console.log(res.data)
})
},
uploadImage(formdata){
return axios({
method:'POST',
url:'http://localhost:3000/article/test2',
data:formdata
})
}
}
}
</script>