您好,登錄后才能下訂單哦!
本篇文章為大家展示了如何在vue項目中利用element_ui實現一個文件上傳功能,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
需求:
1、文件大小驗證
2、文件類型驗證
3、額外參數傳輸
<template> <el-upload class="upload-demo" action :limit="1" :file-list="formFileList" :http-request="handleUploadForm" :on-exceed="formHandleExceed" :on-remove="formHandleRemove" :before-upload="beforeUploadForm" accept=".csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"> <el-button type="primary">上傳文件</el-button> <span slot="tip" class="el-upload__tip" >只能上傳xlsx/xls/csv文件,且不超過{{formMaxSize}}M</span> </el-upload> </template> <script> export default { data () { return { formMaxSize: 10, // 上傳文件大小 formFileList: [], // 顯示上傳文件 uploadFormFileList: [] // 確定上傳文件 } }, methods: { // 開始上傳前驗證 beforeUploadForm (file) { // 驗證文件大小 if (file.size / 1024 / 1024 > this.formMaxSize) { this.$message({ message: `上傳文件大小不能超過${this.formMaxSize}M!`, type: 'warning' }) return false } // 中文亂碼處理 if (file.raw) { let reader = new FileReader() // 讀取文件內容 reader.readAsText(file.raw, 'gb2312') // 防止中文亂碼問題,不加reader.onload方法都不會觸發 reader.onload = function (e) { this.contentHtml = e.target.result // txt文本內容,接下來就可以對其進行校驗處理了 } } // 驗證文件類型 var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1) const extension = testmsg === 'xlsx' || testmsg === 'xls' || testmsg === 'csv' if (!extension) { this.$message({ message: '上傳文件只能是xlsx/xls/csv格式!', type: 'warning' }) } return extension }, // 移除上傳列表中文件 formHandleRemove (file, formFileList) { let thiz = this for (let i = 0; i < thiz.uploadFormFileList.length; i++) { if (thiz.uploadFormFileList[i].pname === file.name) { thiz.uploadFormFileList.splice(i, 1) break } } }, // 允許上傳文件個數驗證 formHandleExceed (files, formFileList) { this.$message.warning(`當前限制選擇 1 個文件,本次選擇了 ${files.length} 個文件,共選擇了 ${files.length + formFileList.length} 個文件`) }, // 上傳文件 handleUploadForm (param) { let thiz = this let formData = new FormData() formData.append('uid', '上傳文件編號') // 額外參數 formData.append('files', param.file) let loading = thiz.$loading({ lock: true, text: '上傳中,請稍候...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' }) thiz.$axios.post('http://localhost:8080/upload/file', formData).then(({data}) => { if (data.statusCode === 233) { thiz.$message('上傳文件成功,' + data.message) thiz.formFileList = [] thiz.uploadFormFileList = [] } else { thiz.formFileList = [] thiz.uploadFormFileList = [] thiz.$message('上傳文件失敗,' + data.message) } loading.close() }) } } } </script> <style lang="scss" scoped> </style>
總結:
關于el-upload中各屬性的配置,可以看element_ui官網
后端接受上傳文件和額外參數:
@RequestParam(value = "uid") String uid, @RequestParam(value = "files") MultipartFile[] files
補充知識:vue利用elementUI上傳文件以及其他參數的處理方式
將文件自動上傳改為false
:auto-upload="false"
點擊保存的時候,調用el-upload的上傳方法
代碼如下(封裝的上傳方法)
export function mpp(data) { return new Promise(function(resolve, reject) { let data = { method: "POST", url:url, data:data } resolve(axios(data)); }) } <template>
<!--導入計劃 --> <div class="associationPlan"> <el-form :model="dataModel" :rules="rules" ref="associationPlan" label-width="100px"> <el-form-item label="項目名稱:" prop="projectArry"> <el-cascader :options="listOrgInfoList" v-model="dataModel.projectArry" :props="defaultProp" size="small" placeholder="請選擇項目" clearable :disabled="isCompany"></el-cascader> </el-form-item> <el-form-item label="計劃級別:" prop="level"> <el-select size="small" v-model="dataModel.level" placeholder="請選擇:" clearable > <el-option v-for="(item,index) in planTypeList" :label="item.name" :value="item.number" :key="index"></el-option> </el-select> <span class="warnInfo" v-if="dataModel.level==1">一級進度計劃匹配項目總工期,項目下只可建立一個,請確認后再添加!</span> </el-form-item> <el-form-item label="計劃名稱:" prop="name"> <el-input v-model.number="dataModel.name" size="small"></el-input> </el-form-item> <el-form-item label="導入計劃:"> <el-upload accept=".mpp" ref="uploadAdd" action="" :auto-upload="false" :http-request="uploadImg" :on-success="uploadImgSuccess" :on-remove="handleRemove"> <el-button size="small" type="success">請選擇文件</el-button> </el-upload> </el-form-item> </el-form> <div class="clickBtn"> <el-button @click="close" size="small">取消</el-button> <el-button @click="commit" size="small" type="primary">保存</el-button> </div> </div> </template>
<script> import { mapState, mapActions } from 'vuex'; import { plan,mpp} from "../api/system_interface.js"; export default { name: "associationPlan", data() { return { dataModel: { projectId: '', projectArry:[], level:null, name:'', parentId:'0' }, defaultProp: { children: "child", label: "name", value: "id" }, //數據校驗 rules: { projectArry: [{ required: true, message: "請選擇項目", trigger: "blur" }], name: [{ required: true, message: "請輸入計劃名稱", trigger: "blur" }], level: [{ required: true, message: "請選擇計劃級別", trigger: "change" }] }, file:false, isCompany:false }; }, computed: { ...mapState([ 'listOrgInfoList', 'planTypeList' ]), }, methods: { ...mapActions([ 'getlistOrgInfoList' ]), update(){ let companyTypes = sessionStorage.getItem("companyType"); this.isCompany = companyTypes == 4?true:false; this.dataModel.projectArry = JSON.parse(sessionStorage.getItem("selectArry")); }, uploadImg (f) { // if(!f){ // this.$message.error("請上傳文件!"); // return // } this.dataModel.projectId = this.dataModel.projectArry[this.dataModel.projectArry.length - 1]; let param = new FormData(); //創建form對象 param.append('file',f.file);//通過append向form對象添加數據 param.append('level',this.dataModel.level);//添加form表單中其他數據 param.append('projectId',this.dataModel.projectId);//添加form表單中其他數據 param.append('planName',this.dataModel.name);//添加form表單中其他數據 mpp(param)//上傳 .then(response=>{ if(response.code == "200"){ this.$message.success("上傳成功!"); this.close(); this.$emit("refreshData"); onSuccess(response.data); } }) .catch(({err}) => { f.onError() }) }, uploadImgSuccess(response, file, fileList) { // 緩存接口調用所需的文件路徑 console.log('文件上傳成功') // this.$message.success("上傳成功!"); }, handleRemove(file, fileList) { // 更新緩存文件 console.log('文件刪除') }, //重置方法 reset() { const associationPlan = this.$refs["associationPlan"]; associationPlan.resetFields(); this.dataModel.projectId = null; this.dataModel.name = ''; this.dataModel.level = ''; this.dataModel.projectArry = []; }, //關閉彈框 close() { this.$emit("close"); this.reset(); }, //點擊提交 commit() { this.$refs["associationPlan"].validate(valid => { if (!valid) { return; } this.$refs.uploadAdd.submit(); // this.dataModel.projectId = this.dataModel.projectArry[this.dataModel.projectArry.length - 1]; // plan(this.dataModel) // .then(response => { // if (response.code == "200") { // this.$message.success("添加成功!"); // this.close(); // this.$emit("refreshData"); // } else { // this.$message.error(response.msg); // } // }) // .catch(error => { // }); }); }, } };
</script> <style lang="scss" scoped> .clickBtn { text-align: center; } .warnInfo{ // color: #feba51; color: rgb(64, 158, 255); } </style>
上述內容就是如何在vue項目中利用element_ui實現一個文件上傳功能,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。