上传功能 使用的是Element UI 提供的 Upload插件
前端:
<template>
<div>
<!-- 上传文件 -->
<el-card style="height:400px;overflow-y:auto;">
<div style="width:250px;">
<el-upload
class="upload-demo"
:action="uploadUrl"
:before-upload='checkFileType'
:limit="1"
:data="uploadParamData"
:on-remove="handleRemove"
ref="test"
:auto-upload="false"
:on-success="afterSuccess"
>
<el-button size="small" type="primary">选择文件</el-button>
</el-upload>
<div slot="tip" class="el-upload__tip" style="margin-top:10px">只能上传<b class="fonta_"> .xlsx </b> 和<b class="fonta_"> .xls </b>文件</div>
<el-button size="small" type="primary" plain @click="submint" style="margin-top:30px">确认上传</el-button>
</div>
</el-card>
</div>
</template>
<script>
export default {
data() {
return {
userInfo: this.$store.state.userBean, //{"userId":"","username":"","deptId":"","dept":""}
/******************************** 上传文件相关 ********************************/
uploadUrl:'', //上传路径
uploadParamData:{ //上传参数
userId:this.$store.state.userBean.userId,
userName:this.$store.state.userBean.username,
UploadFile:'',
},
};
},
methods: {
submint(){
this.$refs.test.submit();// Element UI 提供的提交 方法
},
//上传成功后执行
afterSuccess(response, file, fileList){
console.log('上传结果返回的值=',response)
this.$message.warning(response.returnData);
this.$refs.test.clearFiles();//清空上传列表
},
handleRemove(file) {
return true; //直接删除
},
//检查文件类型
checkFileType(file){
let fileType = file.name.substr(file.name.lastIndexOf('.'),file.name.length-1)
if(fileType!='.xlsx' && fileType!='.xls'){
this.$message.warning(`${file.name} 不符合上传文件类型`);
return false;
}
this.uploadParamData.UploadFile = file.name;
},
},
created(){
this.uploadUrl = `${fss}/dcb/upload`;
}
};
</script>
后端:
/**
* 导入 --->资产信息
* @param request
* @return
* @throws IOException
* @throws DbException
*/
@RequestMapping(value = "/upload",method = RequestMethod.POST)
@ResponseBody
public AjaxJsonResult uploadFile(HttpServletRequest request,@RequestParam("file") MultipartFile file){
AjaxJsonResult ajr = new AjaxJsonResult();
ajr.setOperSuc("上传失败");
try {
String fileName = file.getOriginalFilename(); /*获取文件名*/
String suffixName = fileName.substring(fileName.lastIndexOf(".")); /*获取文件的后缀名*/
System.out.println("获取文件名 ="+fileName);
System.out.println("获取文件的后缀名 ="+suffixName);
String filePath = "C:\\Users\\fan\\Desktop\\图片\\"; /*保存 文件路径*/
File newFile = new File(filePath + fileName);
if (!newFile.getParentFile().exists()) { /*检测是否存在目录*/
newFile.getParentFile().mkdirs();
}
file.transferTo(newFile);
ajr.setOperSuc("上传成功");
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
return ajr;
}
}
注:
@RequestParam("file") MultipartFile file 注解中接收的参数名为 file 和前端传到的值的名字无关 (虽然目前也不知道为啥)