前端封裝el-upload組件,父組件傳值dialogVisible(用于顯示el-dialog),子組件接收,并且關(guān)閉的時(shí)候返回一個(gè)值(用于隱藏el-dialog),最多上傳五個(gè)文件,文件格式為.jpg\pdf\png
<template>
<div>
<el-dialog width="30%" :visible.sync="dialogShow" append-to-body @close='handleCancle' title="上傳發(fā)票" class="uploadDialog">
<!--
list-type="picture"
:file-list="fileList"
:on-change="changeFileLength"
:on-success="handleAvatarSuccess"
multiple
-->
<el-upload
ref="upload"
:auto-upload="false"
:on-remove="handleRemove"
:on-change="changeFileLength"
:limit="5"
:on-exceed="handleExceed"
action="https://jsonplaceholder.typicode.com/posts/"
list-type="picture"
:file-list="fileList"
accept=".pdf,.jpg,.png"
multiple
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">選擇文件</div>
<!-- <div slot="tip" class="el-upload__tip">只能上傳jpg/png/pdf文件,且不超過(guò)500kb</div> -->
</el-upload>
<el-button @click="upload" type="success">上傳文件</el-button>
</el-dialog>
</div>
</template>
<script>
import { upload1 } from "@/api/invoice/invoiceManagement";
import pdfde from "./pdfdefine.png";
export default {
name: "uploadCT",
props:{
dialogVisible:{
type:Boolean,
default:false,
require:true,
}
},
watch: {
dialogVisible: {
handler(val) {
this.dialogShow = val
},
deep: true, // 深度監(jiān)聽(tīng)
immediate: true, // 初次監(jiān)聽(tīng)即執(zhí)行
},
},
data(){
return{
// 上傳文件的列表
uploadFiles: [],
// 上傳文件的個(gè)數(shù)
filesLength: 0,
// 上傳需要附帶的信息
info:{
id:"",
name:"",
},
//顯示
dialogShow:this.dialogVisible,
//縮略圖
fileList:[],
def : pdfde,
}
},
methods:{
//刪除
handleRemove(file, fileList){
console.log("移除");
this.fileList=this.fileList.filter(item=>item.name!=file.name);
this.uploadFiles =this.uploadFiles.filter(item=>item.name!=file.name);
this.filesLength=fileList.length;
},
//超出限制提示
handleExceed(files, fileList) {
this.$message.warning(`當(dāng)前限制選擇 5 個(gè)文件,本次選擇了 ${files.length} 個(gè)文件,共選擇了 ${files.length + fileList.length} 個(gè)文件`);
},
//關(guān)閉
handleCancle(){
this.uploadFiles= [];
// 上傳文件的個(gè)數(shù)
this.filesLength= 0;
this.dialogShow = false;
this.$emit('closeUploadDialog',this.dialogShow);
this.$refs.upload.clearFiles();
this.fileList=[];
},
// 選擇文件觸發(fā)事件
changeFileLength(file, fileList){
console.log("選擇",file,fileList);
this.filesLength = fileList.length;
if(file.name.endsWith('.pdf')){
this.fileList.push({
name:file.name,
url: this.def,
})
}else{
this.fileList.push({
name:file.name,
url:file.url,
})
}
this.uploadFiles=fileList;
},
// 用戶點(diǎn)擊上傳調(diào)用
async upload(){
// 觸發(fā)上傳 調(diào)用配置 :http-request="uploadFile"
// 即觸發(fā) uploadFile函數(shù)
console.log('點(diǎn)擊',this.filesLength);
if(this.filesLength>0){
this.fileList[0].staus='ready';
// await this.$refs.upload.submit();
await this.uploadFilesToService();
// 上傳完成后執(zhí)行的操作 ...
}else{
this.$modal.msgError( "請(qǐng)先選擇文件");
}
},
//上傳按鈕
async uploadFilesToService(){
console.log("上傳",this.uploadFiles.length,this.filesLength);
let that = this;
if (this.uploadFiles.length == this.filesLength){
// 創(chuàng)建FormData上傳
let fd = new FormData()
// 將全部文件添加至FormData中qingxian
this.uploadFiles.forEach(file => {
fd.append('file', file.raw)
})
// 將附加信息添加至FormData
fd.append("id", this.info.id)
fd.append("name", this.info.name)
// 配置請(qǐng)求頭
const config = {
headers: {
"Content-Type": "multipart/form-data",
}
}
console.log("參數(shù)",fd);
// 上傳文件
await upload1(fd).then(res => {
/*上傳成功處理*/
console.log(res);
if(res.msg=='上傳成功'){
this.uploadFiles=[];
this.filesLength = 0;
this.dialogShow = false;
this.$emit('closeUploadDialog',this.dialogShow);
this.$refs.upload.clearFiles();
this.uploadFiles = [];
this.filesLength = 0;
this.fileList = [];
this.$refs.upload.clearFiles();
this.$modal.msgSuccess("上傳成功");
}else{
console.log("失敗");
const arr1 =res.data.data;
this.$nextTick(()=>{
arr1.map(item1=>{
this.uploadFiles = this.uploadFiles.filter(item2=>item2.name!=item1);
this.fileList = this.fileList.filter(item=>item.name!=item1);
})
})
this.filesLength=this.filesLength-arr1.length;
console.log(this.uploadFiles,this.filesLength);
this.$modal.msgError(res.data.msg);
}
}).catch(err => {/*報(bào)錯(cuò)處理*/console.log("報(bào)錯(cuò)",err);});
}
}
}
}
</script>
后端接收
@PostMapping("/upload")
public AjaxResult upload(@RequestParam(value = "file") MultipartFile[] file)
{
ArrayList<String> successList = new ArrayList<>();
try {
String localPath = "";
//1.1獲取當(dāng)前日期,當(dāng)做本地磁盤(pán)的目錄
Date nowDate = DateUtils.getNowDate();
String format = new SimpleDateFormat("YYYYMMDD").format(nowDate);
String localPathPrefix = "C:\\"+format;
for(MultipartFile f:file){
// 獲取文件名
String fileName = f.getOriginalFilename();
// 獲取文件后綴
String prefix = fileName.substring(fileName.lastIndexOf("."));
// 保存文件到本地磁盤(pán)
localPath = localPathPrefix+"\\"+fileName;
File localFile = new File(localPath);
if (!localFile.getParentFile().exists()) {
localFile.getParentFile().mkdirs();
}
//寫(xiě)入到本地磁盤(pán)
f.transferTo(localFile);
// 獲取文件在本地磁盤(pán)上的路徑
String filePath = localFile.getAbsolutePath();
log.info("文件名稱:"+fileName+"已經(jīng)存入本地磁盤(pán),全路徑為:"+filePath);
//成功一個(gè),將文件名放入一個(gè)successList
int i = finInvoiceDefineService.OCRToService(filePath);
//刪除本地臨時(shí)磁盤(pán)文件
if (localFile.delete()) {
log.info(localFile.getName() + "已經(jīng)刪除");
} else {
log.info("文件刪除失敗");
}
}
//刪除本次磁盤(pán)的日期目錄
File file1 = new File(localPathPrefix);
if (file1.delete()) {
log.info(file1.getName() + "已經(jīng)刪除");
} else {
log.info("文件刪除失敗");
}
}catch (Exception e){
log.error(e.toString());
HashMap<String, Object> stringObjectHashMap = new HashMap<>();
stringObjectHashMap.put("msg","OCR識(shí)別失敗");
stringObjectHashMap.put("data",successList);
return success(stringObjectHashMap);
}
return success("上傳成功");
}
效果展示
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-661026.html
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-661026.html
到了這里,關(guān)于vue實(shí)現(xiàn)文件上傳,前后端的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!