写文件上传时,在网上看过很多关于upload组件文章,今天我就总结下自己运用upload组件的心得。
最有力的说明就是代码了,上代码
1.运用iview upload组件上传文件(带token,带参数)
1.1. 前端vue代码
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'),
}
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
}
}
1.2. 后端java代码(在网上找了许久都没找到,无奈中尝试出来了)
@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代码
1. 组件 <div style="align-items:center;display:flex;justify-content:flex-start;"> <Upload style="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; }