寫文件上傳時,在網上看過不少關於upload組件文章,今天我就總結下本身運用upload組件的心得。前端
最有力的說明就是代碼了,上代碼vue
1.運用iview upload組件上傳文件(帶token,帶參數)java
1.1. 前端vue代碼ios
1.組件
<div style="align-items:center;display:flex;justify-content:flex-start;"> <Upload action="/myblog/mycontroller/mymethod" :headers="{'Authorization':token}" :data="fileData" :before-upload="onBefore" style="margin-left: 5px;"> <Button icon="ios-cloud-upload-outline"style="margin-top: 8px;" type="primary" size="large" >導入</Button> <!--<span v-if="file !== null" style="color:green;">{{ file.name }}</span>--> </Upload> </div>
2.變量
data () {
return {
file:null,
fileData:{'groupName':'default'},
token:'Bearer' + Cookies.get('token'),
}axios
3.函數
onBefore(file){
let exceededNum=file.name.lastIndexOf(".");
let exceededStr=file.name.substring(exceededNum+1,file.name.length).trim();
if(exceededStr!="csv"){
this.$Notice.warning({
title: '文件格式錯誤',
desc: file.name + '文件格式不正確, 請選擇 csv'
});
return false;
}
if(file.size>(102400*20)){
this.$Notice.warning({
title: '文件大小錯誤',
desc: file.name + '文件大小太大,超過2M'
});
return false;
}
this.file=file;
return true;
},後端
4.監聽變量(更新參數值)
watch: {//與生命鉤子(created函數)同級
groupName: {
handler: function(groupName) {
this.fileData={'groupName':groupName}
},
deep: true
}
}app
1.2. 後端java代碼(在網上找了許久都沒找到,無奈中嘗試出來了)iview
@RequestMapping(value = "/uploadAccountFile", method = RequestMethod.POST) @ResponseBody public String uploadAccountFile(@RequestParam MultipartFile file,@RequestParam String groupName) {//不須要參數可去掉 @RequestParam String groupName
//也可換成 HttpServletRequest request, HttpServletResponse response String result= null; try { InputStream is = file.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); reader.readLine(); String line = null; while((line=reader.readLine())!=null){ } result = "絕世神功九陽真經終於練成,天上地下任我逍遙,哈哈哈"; } catch (Exception ex) { result = "迫不得已走火入魔,來世再見"; } return result; }
2. 運用iview upload組件手動上傳文件函數
2.1. 前端vue代碼post
1. 組件 <div style="align-items:center;display:flex;justify-content:flex-start;"> <Upload style="width:80%;" :action="url" :before-upload="onBefore"> <Button icon="md-cloud-upload">點擊上傳</Button> <span v-if="file !== null" style="color:green;">{{ file.name }}</span> </Upload> </div>
2.變量
data() {
return {
url: '',
file: null,
name: '',
note: ''
}
}
3.函數
onBefore(file) {
this.file = file;
return false;
},
doupload() {
this.$store.dispatch({
type: 'doupload',
'name': this.name,
'note': this.note,
'file': this.file
}).then(res => {
console.log('res:' + res)
}, err => {
console.log('doupload-err:' + err);
});
},
4.請求
doupload({
commit
}, payload) {
return new Promise((resolve, reject) => {
let fd = new FormData();
fd.append('name', payload.name);
fd.append('note', payload.note);
fd.append('file', payload.file);
let config = {
timeout:300000,
onUploadProgress: progressEvent => {
var complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
console.log('上傳進度:'+complete);
},
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': 'x-requested-with,content-type',
'Content-Type': 'multipart/form-data',
}
};
axios.post('/myblog/mycontroller/mymethod', fd,config).then(function(res){
resolve(res);
}).catch(function(err){
reject(err);
});
});
},
2.2 後端java代碼
@RequestMapping("/doupload") public ModelAndView doupload( @ApiParam(required=true, value="名稱")@RequestParam String name, @ApiParam(required=false, value="備註") @RequestParam String note, @ApiParam(required=true, value="文件") @RequestParam("file") MultipartFile file) { try { if (file.isEmpty()) { throw new DoubleComException("文件未上傳"); } }catch(Exception e) { logger.error(e.getMessage(), e); } ModelAndView mav = new ModelAndView("redirect:page"); return mav; }