vue 文件上传自定义实现

vue的文件上传组件 upload ,拥有支持多种格式文件上传,单文件多文件等都支持,许多项目现在都少不了文件上传功能,但是vue 的upload组件如果直接引用,肯定也有一些不方便之处,有的时候需要传参数,需要手动触发上传方法,而不是选择了文件就上传,所以结合我项目实例,写一vue 自定义文件上传的实现,包括前端和后台的处理以及参数的接收。

一、先认识一下vue 的upload组件,官网链接 http://element-cn.eleme.io/#/zh-CN/component/upload,这里不多做解释,大家自己看

二、使用

   这个组件有多种样式,我在这里只展示一种,如图所示

代码:

<template>
<div>
<el-dialog title="导入数据" :visible="visible" @close="close" width="400px">
<el-upload ref="upload"         //ref属性值一定要有,提交的时候会用到
class="upload-demo"
drag
:action="url"        //此处的url是从父页面传过来的动态值,不同页面引用,可能请求的后台地址不一样,所以定义了一个变量接收
:multiple="false" 
:before-upload="beforeUpload"     //上传之前调用的方法,验证,格式限制等等,大小限制都可以在这个方法中实现
:limit=1     //个数限制
:auto-upload="false"  //是否立即上传,默认为true
:on-exceed="handleExceed" //文件超出个数限制时的钩子
:http-request="uploadFile">  //自定义提交方法
 
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传.xlsx文件</div>
<div class="el-upload__tip" slot="tip">一次只能上传一个文件</div>
</el-upload>
<div slot="footer" class="dialog-footer">
<el-button :visible="visible" @click="close()">取 消</el-button>         //visible 控制页面关闭打开,从父页面传过来初始值,close()关闭页面
<el-button type="primary" @click="submitUpload">确定上传</el-button> //上传
</div>
</el-dialog>
</div>
</template>

<script>
export default {
props:{visible:false, //父页面传递参数
initData:{}, //父页面传递参数
url:""  //父页面传递上传url
},
watch: {  //监听参数值改变
initData(newValue,oldValue){
this.getData(newValue);
console.log("newValue2333",newValue);
}
},
data() {
return {
params:{},
}
},
mounted(){
},
methods:{
close() {
this.$emit("update:visible", false);
},
beforeUpload (file) {  //设置只能上传excel文件
console.log('beforeUpload')
console.log(file.type)
const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
if(isExcel){
return true;
}else{
this.$message.warning(`只能上传excel文件`)
return false;
}
},
// 上传文件个数超过定义的数量
handleExceed (files, fileList) {
this.$message.warning(`当前限制选择 1 个文件,请删除后继续上传`)
},
// UploadUrl:function(){
// return
// },
getData(initData){   //参数值改变重新赋值
this.params=initData;
},
//确认上传
submitUpload(){
this.$refs.upload.submit();
},
//开始上传文件
uploadFile(content){
console.log("uploadFile",content);
const formData=new FormData();
formData.append("file",content.file);
formData.append("params",this.params);    //后台接收param时可以vue可以先将params转成json字符串,后台接收一个json字符串再遍历,自己百度
//发送请求
console.log(this.params);
this.commonPost({
url:content.action,
params:formData,
timeout:2000,
}).then(data=>{
this.$message({
type:"success",
message:"上传文件成功"
});
//关闭上传弹出框
this.close();
})
}
}
};
</script>
 
由于我这个是做的一个公共组件,可以作为其他页面的一个组件给放进去,所以会有一些特别之处,,大部分在代码中都有注释。
 
三、父页面部分代码
<!--导入窗口-->
<InportExcel :visible.sync="inportExcelVisible" :initData="fileData" :url="urlString"></InportExcel>   在需要的地方引用这句话,
 
import InportExcel from '@/api/pfm/common/InportExcel';   //引入InportExcel
 
watch:{
headerId:function(val,oldval){
if(val && val != -1){
this.fileData={};          //参数监听
this.fileData.currentHeaderId=val; //参数赋值
this.urlString=" http://localhost:8080/pfm/file/upFile"; //url赋值
 
}
}
 
components:{      //InportExcel注册
InportExcel:InportExcel
}
 
 
四、后台代码处理
1、controller
@PostMapping("/upFile")
public Object upLoadFile(@RequestParam("file") MultipartFile file,@RequestParam("params") String params,
HttpServletResponse response,HttpServletRequest request){
Workbook workbook=null;
try{
if(params!=null){
JSONObject json=JSONObject.parseObject(params);
if(json.containsKey("currentHeaderId")){
System.out.println(json.get("currentHeaderId").toString());
}
}
workbook= fileService.uploadFile(file,request,response);
}catch (Exception e){
logger.info(e.getMessage());
}
return workbook;
}

 2、service实现

@Override
public Workbook uploadFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
checkFile(file);
System.out.println(file);
return getWorkBook(file);
//接收文件

}
public static void checkFile(MultipartFile file) throws IOException {
if(null==file){
logger.info("文件不存在");
throw new FileNotFoundException("文件不存在");
}
String fileName=file.getOriginalFilename();
System.out.println(fileName.endsWith("xls"));
if(!fileName.endsWith("xls")&&!fileName.endsWith("xlsx")){
logger.info("不是excel文件");
throw new IOException(fileName+"不是excel文件");
}
}
public static Workbook getWorkBook(MultipartFile file){
String fileName=file.getOriginalFilename();
Workbook workbook=null;
try{
InputStream is=file.getInputStream();
if(fileName.endsWith("xls")){
workbook=new HSSFWorkbook(is);
}else if(fileName.endsWith("xlsx")){
workbook=new XSSFWorkbook(is);

}
}catch (IOException e){
logger.info(e.getMessage());
}
return workbook;
}

3、注,本次后台代码只针对excel文件,如果是其他文件,也可以进行百度,处理方法很简单
原文地址:https://www.cnblogs.com/szy-wang/p/10475130.html