最近项目碰到一个需求,上传附件,平时上传附件做的很多,比如上传个图片,然后还可以预览,这是稀松平常的功能,但是这次这个上传客户要求不限制文件类型,什么都能上传,什么Excel,word,ppt,txt,图片,视频,音乐等等,关键是上传的时候还需要用户看到上传的东西,方便用户确认,我们知道图片上传预览其实也不是展示的客户端物理机上的图片(浏览器出于安全考虑是不会让我们获取到客户端物理机上面的文件的真实路径的),而是我们选择的图片文件的binary,其实就是二进制文件,也就是预览是把我们选择的图片的二进制文件转成图片让我们看到。为了解决这个需求,就有了这篇文章。
效果图:
前端代码:
定义组件
<template>
<div>
<v-button-search @click="uploadExcel" style="float:right;">上传附件</v-button-search>
<el-dialog title="上传文件" :visible.sync="dialogTableVisible">
<div style="width:100%;height:200px;">
<el-upload
ref="upload"
:limit="5"
:action="uploadUrl"
:on-remove="handleRemove"
:on-error="uploadFalse"
:on-success="uploadSuccess"
:auto-upload="true"
:before-upload="beforeUpload"
:show-file-list="false"
>
<el-button slot="trigger" size="small" type="primary">选择上传</el-button>
<!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">提交附件</el-button>-->
</el-upload>
<div v-if="showPreview">
<h4 style="font-weight:500;height:15px;">已上传发票附件确认(点击文件名称下载查看确认):</h4><br><br>
<template v-for="(value,index) in attachedUrls">
<div style="width: 100%;"><a :href='attUrl+value'>{{value.substring(value.indexOf('_')+1,value.length)}}</a><i @click="deleteUrl(value)" class="el-icon-delete" style="float: right;"></i></div>
</template>
</div>
</div>
</el-dialog>
</div>
</template>
<style>
.el-upload__input {
display: none !important;
}
</style>
<script>
import Vue from "vue";
import RemarksUpload from '../../../../static/project/js/remarksUpload-file.js';
export default {
props: ["uploadUrl"],
data() {
return {
uploadFiles:[],
attachedUrls:[],
dialogTableVisible: false,
showList:true,
showPreview:false,
attUrl:'http://127.0.0.1:8088/server/invoice/downFile?name='
};
},
mounted() {},
methods: {
// 上传
uploadExcel() {
this.dialogTableVisible = true;
},
beforeUpload(file) {
this.loading = this.$loading({
lock: true,
text: "上传中.......",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.7)"
});
this.files = file;
return true;
},
uploadSuccess(response, file, fileList) {
if (response.success) {
this.uploadFiles.push(response.data);
this.attachedUrls.push(response.data);
RemarksUpload.$emit('demo','msg');
if(this.uploadFiles.length==fileList.length){
alert("文件上传成功");
this.showList=false;
this.showPreview=true;
// this.dialogTableVisible=false;
}
} else {
this.loading.close();
alert("《" + file.name + "》" + response.data);
}
this.loading.close();
},
uploadFalse(err, file, fileList) {
this.loading.close();
alert(err.name)
alert("文件上传失败......!");
},
submitUpload() {
this.$refs.upload.submit();
},
handleRemove(file, fileList) {
},
deleteUrl(value){
this.$confirm("确认删除?","确认删除",{
confirmButtonText: "确定",
cancelButtonText: "取消"
}).then(()=>{
this.uploadFiles.splice(this.uploadFiles.indexOf(value),1)
this.attachedUrls.splice(this.attachedUrls.indexOf(value),1)
alert("附件已删除");
}).catch(() => {
this.loading.close();
});
}
}
};
</script>
remarksUpload-file.js文件内容:
import Vue from 'vue'
export default new Vue
暴露组件
import FilesUpload from "../../components/common/dialog/files-upload.vue";
Vue.component("v-files-upload", FilesUpload);
使用组件
<v-files-upload :uploadUrl="uploadUrl" ref="childtag" v-if="hasPermssion('invoiceDataOperate')"></v-files-upload>
this.permissions = this.$getSessionPermission();
uploadUrl: this.GLOBAL.ProjectUrl.fileUpload
hasPermssion(name) {
if (this.permissions != null && this.permissions.indexOf(name) >= 0) {
return true;
} else {
return false;
}
},
this.submitFormArray[0]["url"]=this.$refs.childtag.uploadFiles;
后台代码:
接口:
@RequestMapping(value = "/upload", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public AjaxForm addFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws Exception {
AjaxForm ajaxForm = new AjaxForm();
try {
File localFile = ExcelReadUtil.saveFile(file);
ajaxForm.setData(localFile.getName());
ajaxForm.setSuccess(true);
} catch (Exception e) {
ajaxForm.setSuccess(false);
ajaxForm.setData(e.getMessage());
e.printStackTrace();
}
return ajaxForm;
}
上传下载工具类中的方法:
public static File saveFile(MultipartFile file) throws Exception {
if (file == null) {
throw new Exception("file is null");
}
if (file.isEmpty()) {
throw new Exception("文件为空");
}
//upload_file是文件上传的路径,写在配置文件中
String path = ProjectConfigUtil.get("upload_file");
// 获取上传的文件名称,并结合存放路径,构建新的文件名称
String filename = StringUtil.getFileNameBySysDate() + "_" + file.getOriginalFilename();
File localFile = new File(path, filename);
//如果目录不存在,创建目录
if (!localFile.getParentFile().exists()) {
localFile.getParentFile().mkdirs();
}
//文件移动
file.transferTo(localFile);
return localFile;
}
```