後臺管理系統三部曲之——第一部曲實現檔案的上傳
阿新 • • 發佈:2020-10-16
實現檔案上傳
把檔案上傳封裝成一個元件:
<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) }) }) }