之前在html中上傳圖片常常使用form表單,然後在vue裏面是可以使用element-ui中upload組件,那麼如何進行正確的上傳呢?
vue組件界面代碼
<template>
<div>
<el-upload action="string"
:multiple="true"
:before-upload="beforeupload"
:show-file-list="false">
<el-button size="mini" type="primary" @click="clearUpload">導入</el-button>
</el-upload>
<el-button size="mini" type="primary" @click="submitUpload">手動上傳</el-button>
</div>
</template>
<script>
export default {
data() {
return {
uploadForm: new FormData(),
}
},
methods: {
//獲取文件
beforeupload(file) {
console.log(file)
this.uploadForm.append('file', file);
console.log(this.uploadForm.get("file"))
return false;
},
clearUpload() {
this.uploadForm = new FormData();
},
//手動上傳
submitUpload() {
console.log(this.uploadForm)
let data = this.uploadForm;
this.$axios({
url: '/od/postImg',
method: "post",
data: data,
headers:{
a:'file'//進行驗證 之後會見到,如果不需要進行驗證可以不寫headers
},
processData: false,//必寫
contentType: false,//必寫
success: function (rs) {
if (rs.data.state == '0')
MessageBox({title: '提示', message: '導入成功!', type: 'success'});
else
MessageBox({title: '提示', message: '導入失敗!', type: 'error'});
}
});
}
}
}
</script>
以上代碼爲vue代碼,需要注意的幾點就是 需要設置關閉自動上傳使用手動上傳,並且定義FormData()對象,FormData對象
表單對象,也就是說它可以使用formdata.append("xxx")封裝一個表單請求,其中xxx也就是我們之前的<input type="file" name="xxx"> 。
請注意!! 你不能使用
console.log(this.uploadForm)因爲這個是打印顯示爲null,可以使用 console.log(this.uploadForm.get("file")),但是這也是僅僅顯示第一個對象,所以不會擔心。
重點
----------------
也許你試過好幾種百度的方式,但是每一個都沒請求成功,很有可能是請求類型的錯誤!!!。
首先是必須爲post請求,默認爲content-type爲json,但是如果data爲formData的時候, content-type會是multipart/form-data
所以我們在進行請求的時候沒必要寫header定義content-type,vue會進行添加的。
比如我寫的
his.$axios({
url: '/od/postImg',
method: "post",
data: data,
headers:{
a:'file'//進行驗證 之後會見到,如果不需要進行驗證可以不寫headers
},
processData: false,//必寫
contentType: false,//必寫
success: function (rs) {
if (rs.data.state == '0')
MessageBox({title: '提示', message: '導入成功!', type: 'success'});
else
MessageBox({title: '提示', message: '導入失敗!', type: 'error'});
}
});
僅僅只需要發送一個post請求然後data使用formData對象即可,springboot後端使用 RequestParam("xxx")來指定name的表單字段。
@PostMapping(value = "/postImg")
public Result postImg(@RequestParam("file")MultipartFile[] file ){
String uploadFilePath = imgUploadServer.getUploadFilePath(file[0]);
System.out.println(uploadFilePath);
return new Result(ResultCode.SUCCESS);
}
-----------------------------------------------------------------------------------
寫到這你可能還會失敗,對不對??
別擔心!!!只要找到方式就能解決的。
首先我們前端傳入content-type multipart/form-data,後端使用@RequestParam("file")MultipartFile[] file接收是沒錯的。
但是有可能你設置了http request 攔截器
axios.interceptors.request.use(
config => {
if (config.headers.a != null) {
} else {
config.data = JSON.stringify(config.data);
config.headers ={
"Content-Type":"application/json;charset=UTF-8",
}
}
return config;
},
error => {
return Promise.reject(err);
}
);
)
然後這會把你data進行JSON序列化,作孽呢!!!!,所以你懂的,去掉,但是或者說寫了很多接口都需要轉爲JSON序列化,那麼就加一個if判斷了。
------------完結 。(如還有錯誤,可以諮詢我哦)