1. 程式人生 > 程式設計 >vue+element_ui上傳檔案,並傳遞額外引數操作

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" style="margin: 0 10px;">只能上傳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.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="請選擇專案" style="width:100%;" clearable :disabled="isCompany"></el-cascader>
    </el-form-item>
     <el-form-item label="計劃級別:" prop="level">
      <el-select size="small" v-model="dataModel.level" placeholder="請選擇:" clearable style="width:100%;">
        <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" style="display:inline-block;vertical-align: top;" 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: "請輸入計劃名稱",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上傳檔案,並傳遞額外引數操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。