实现文件上传
把文件上传封装成一个组件:
<template v-if="fileId"> <el-tag :closable="dealerStatus !== '2'" @close="deleteFile(fileId)"> {{ fileName }} </el-tag> </template> <template v-else> <el-upload v-if="dealerStatus !== '2'" class="avatar-uploader" :action="actionUrl" drag :before-upload="beforeUpload" accept=".jpg, .png, .jepg, .pdf" :show-file-list="false" :on-change="changeUpload" > <el-button type="primary" class="upload" plain> 点击上传 </el-button> </el-upload> </template>
beforeUpload(file) { console.log(this.fileCategory, "文件类型"); if (file) { console.log(file, "文件结构"); if ( ["image/jpeg", "image/jpg", "image/png", "application/pdf"].indexOf( file.type ) === -1 ) { // if (file.name.indexOf('jpg') !== -1 || file.name.indexOf('png') !== -1 || file.name.indexOf('jepg') !== -1 || file.name.indexOf('pdf') !== -1) { this.$message.error("文件格式错误"); return false; } const formData = new FormData(); formData.append("file", file); console.log(file, "文件名"); CommonAPI.AsyncUpload(this.actionUrl, formData) .then((res) => { if (res.code === 200) { this.$emit( "fileUpload", { fileCategory: this.fileCategory, fileName: file.name, filePath: res.data, fileId: res.data, }, this.index ); console.log(res); } else { this.$message({ type: "error", message: res.msg, }); } // 根据返回 code }) .catch((error) => { // debugger; console.log(error) } return false; },
接口文件:
//上传-导入 const AsyncUpload = (url, data) => { return new Promise((resolve, reject) => { requestUpload({ url: url, method: 'post', headers: { 'Content-Type': 'multipart/form-data' }, data }).then((res) => { resolve(res) }).catch((error) => { reject(error) }) }) }