溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

vue+element-ui+axios多文件上傳怎么實(shí)現(xiàn)并顯示整體進(jìn)度

發(fā)布時(shí)間:2022-04-11 14:04:44 來源:億速云 閱讀:260 作者:iii 欄目:開發(fā)技術(shù)

今天小編給大家分享一下vue+element-ui+axios多文件上傳怎么實(shí)現(xiàn)并顯示整體進(jìn)度的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

element-ui+axios多文件上傳并顯示進(jìn)度

element-ui自帶的多文件上傳是做成了多文件多次上傳,公司有需求需要選取多個(gè)文件一次上傳全部.

代碼部分

<template>
  <d2-container>
    <el-form ref="form" :model="formData" label-width="120px">
      <el-row>
        <el-col :span="10">
          <el-form-item label="圖片"  prop="mediaFileUrl">
            <el-upload 
              class="upload-demo"
              ref="uploadMul"
              multiple
              action
              drag
              :limit="maxUploadSize"
              :on-exceed="uploadLimit"
              :http-request="uploadFile"
              :file-list="fileList"
              :auto-upload="false"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :on-change="uploadChange"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">將文件拖到此處,或<em>點(diǎn)擊上傳</em></div>
              <div class="el-upload__tip" slot="tip">支持上傳jpg/png/gif文件,且不超過100M</div>
            </el-upload>
            <div v-show="progressFlag" class="head-img">
              <el-progress :text-inside="true" :stroke-width="14" :percentage="progressPercent" status="success"></el-progress>
            </div>
            <el-button size="mini" type="success" @click="submitUpload">上傳到服務(wù)器</el-button>
            <el-button v-if="this.fileList.length > 0" size="mini" type="warning" @click="clearFiles">清空</el-button>
          </el-form-item>
        </el-col>
        <el-col :offset="4"></el-col>
      </el-row>
    </el-form>
  </d2-container>
</template>
<script>
import axios from 'axios'
export default {
  data () {
    return {
      maxUploadSize: 10,
      progressFlag: false,
      progressPercent: 10,
      innerVisible: false,
      fileList: [],
      isViewDisabled: false,
      formData: {},
      param: {} // 上傳文件主要參數(shù)
    }
  },
  methods: {
    submitUpload () {
      if (this.fileList.length < 1) {
        this.$message.warning('請(qǐng)選擇文件!')
        return false
      }
      this.$refs.uploadMul.submit()
      if (this.param instanceof FormData) {
        // 附加參數(shù)
        this.param.append('expirationsec', 0)
        this.param.append('fileproperty', 'publicfiles')
        // const config = {
        //   headers: { 'content-type': 'multipart/form-data' }
        // }
        // axios.post('/api/oss/ossUploadObject', this.param, config).then(res => {
        //   if (res.status === 200 && res.data.status === 200) {
        //     this.$message.success('上傳成功!')
        //     let result = res.data.body.data
        //     console.log(result)
        //   }
        //   this.$refs.uploadMul.clearFiles()
        //   this.param = {}
        // })
        let that = this
        that.progressFlag = true
        axios({
          url: '/api/oss/ossUploadObject',
          method: 'post',
          data: that.param,
          headers: { 'Content-Type': 'multipart/form-data' },
          onUploadProgress: progressEvent => {
            // progressEvent.loaded:已上傳文件大小
            // progressEvent.total:被上傳文件的總大小
            // 進(jìn)度條
            that.progressPercent = ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0) | 0
          }
        }).then(res => {
          this.param = {}
          this.fileList = []
          console.log(res)
          if (res.data.status === 200 && that.progressPercent === 100) {
            setTimeout(function () {
              that.$message({
                message: '上傳成功!',
                type: 'success',
                duration: '2000'
              })
              that.progressFlag = false
              that.progressPercent = 0
              that.$refs.uploadMul.clearFiles()
            }, 1000)
            let result = res.data.body.data
            console.log(result)
          } else {
            setTimeout(function () {
              that.$message({
                message: res.data.msg,
                type: 'error',
                duration: '2000'
              })
              that.progressFlag = false
              that.progressPercent = 0
              that.$refs.uploadMul.clearFiles()
            }, 1000)
          }
        }).catch(() => {
          that.progressFlag = false
          that.progressPercent = 0
          that.$refs.uploadMul.clearFiles()
          that.$message({
            message: '上傳失敗!',
            type: 'error',
            duration: '2000'
          })
        })
      } else {
        console.log(this.param instanceof FormData)
      }
    },
    handleRemove (file, fileList) {
      this.$message.warning(`已移除文件:  ${file.name}!`)
      // 每移除一個(gè)文件,param重新賦值
      this.param = new FormData()
      this.fileList = [...fileList]
      this.fileList.forEach((file, index) => {
        this.param.append(`file`, file.raw) // 把單個(gè)文件重命名,存儲(chǔ)起來(給后臺(tái))
      })
    },
    uploadChange (file, fileList) {
      // const videoType = ['image/gif', 'image/png', 'image/jpeg', 'video/mp4', 'video/flv', 'video/avi', 'video/rmvb']
      // if (videoType.indexOf(file.raw.type) === -1) {
      //   this.$message.error(`不支持此文件格式${file.raw.type}`)
      //   this.$refs.uploadMul.clearFiles()
      //   return false
      // }
      this.param = new FormData()
      this.fileList = [...fileList]
      this.fileList.forEach((file, index) => {
        this.param.append(`file`, file.raw) // 把單個(gè)文件重命名,存儲(chǔ)起來(給后臺(tái))
      })
    },
    // 超出上傳個(gè)數(shù)時(shí)調(diào)用
    uploadLimit (files, fileList) {
      this.$message.error(`最多允許同時(shí)上傳${this.maxUploadSize}個(gè)文件!`)
      // files.forEach((file, index) => {
      //   console.log(index)
      // })
    },
    beforeUpload (file) {
    },
    uploadFile (file) {
      // 該方法需存在,防止空action時(shí)element-ui報(bào)404異常
    },
    clearFiles () {
      this.fileList = []
      this.param = {}
      this.$refs.uploadMul.clearFiles()
    },
    // 初始化表單數(shù)據(jù)
    init () {
    }
  }
}
</script>
<style lang="scss" scoped>
</style>

后端代碼(模擬)

@RequestMapping("/oss/ossUploadObject")
public ApiResponse<FileDto> uploadObject(@RequestParam("file") MultipartFile[] file, FileVo fileVo){
    //...code
    FileDto dto = new FileDto();
    dto.setUrl("");
    dto.setFileId("");
    return ApiResponse.success(FileDto);
}

解決element ui多文件上傳的問題

業(yè)務(wù)場景

在使用vue+elementui 實(shí)現(xiàn)文件上傳的時(shí)候,我發(fā)現(xiàn)官網(wǎng)給的組件每次都會(huì)自動(dòng)上傳,而且一次上傳一個(gè)文件。但是我實(shí)際的業(yè)務(wù)是,一次上傳多個(gè)文件。

解決辦法

前端代碼:

<template>
  <div>
<!--    文件上傳組件-->
<!--      :auto-upload="false" 這里設(shè)置為不自動(dòng)上傳 ,所以:action="BASE_API+'/upload'“ 失效-->
  <el-upload
    name="files"
    class="upload-demo"
    :on-change="OnChange"
    :multiple="true"
 
    :action="BASE_API+'/upload'"
    :on-preview="handlePreview"
    :before-remove="beforeRemove"
    :file-list="list"
    :auto-upload="false"
    list-type="picture">
    <i class="el-icon-plus"></i>
    <div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過500kb</div>
  </el-upload>
  <el-dialog :visible.sync="dialogVisible">
    <img width="100%" :src="dialogImageUrl" alt="">
  </el-dialog>
  <el-button type="" @click="fun">點(diǎn)擊查看filelist</el-button>
  <el-button type="" @click="onSubmit">提交</el-button>
  </div>
 
</template>
<script>
  import upload from "@/api/upload"
  import request from "@/utils/request"
 
  export default {
    data() {
      return {
        param: new FormData(),
        form:{},
        count:0,
        list:[],
        dialogVisible:false,
        dialogImageUrl:'',
        BASE_API: process.env.BASE_API, // 接口API地址
      };
    },
    methods: {
      handlePreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`確定移除 ${ file.name }?`);
      },
      OnChange(file,fileList){
 
        console.log(fileList)
        this.list=fileList
 
      },
      OnRemove(file,fileList){
        this.list=fileList
      },
      fun(){
        console.log('------------------------')
        console.log(this.list)
      },
      onSubmit(){
 
        // this.form={
        //   a:1,
        //   b:2,
        //   c:3
        // }
        // let file=''
        // for(let x in this.form){
        //   this.param.append(x,this.form[x])
        // }
        // for(let i=0;i<this.list.length;i++){
        //    const file='file'+this.count
        //   this.count++
        //   this.param.append(file,this.list[i].raw)
        // }
        // console.log(this.param)
 
        console.log(this.list[0])
 
        let formData = new FormData();
        let file1 = this.list[0]
        let file2 = this.list[1]
        console.log(file1)
        console.log(file2)
        // 這里必須是 .raw 不然后端springboot multipart 獲取到的文件為 null
        // 單個(gè)文件的話 后端接口寫 Multipart file
        // 多個(gè)文件的話 后端接口寫 Multipart [] files
        // 文件名需要對(duì)應(yīng)
        formData.append('files', file1.raw);
        formData.append('files', file2.raw);
        // formData.append('name', 'zhangsan');
        // formData.append('files[]', file2);
 
        request.post('/upload',formData,{
          headers: {
            'Content-Type': 'multipart/form-data'
          }}).then(res=>{
          console.log(res)
        })
 
        // request.post('/testabc?name='+formData.get("name")).then(res=>{
        //   console.log(res)
        // })
 
        // upload.uploadfile(formData).then(res=>{
        //   console.log(res)
        // })
        // batchTagInfo(this.param)
        //   .then(res=>{
        //     alert(res)
        //   })
      }
    }
  }
</script>
 
<style scoped>
</style>

后端接口代碼:

package com.yj.wiki.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
 
@RestController
@CrossOrigin
public class UploadFileController {
 
    @PostMapping("/upload")
    public String upload(MultipartFile[] files){
 
        for (MultipartFile file : files) {
            System.out.println(file.getOriginalFilename());
 
        }
 
        return "ok";
    }
 
    @PostMapping("/testabc")
    public String upload(String name){
 
        System.out.println(name    );
 
        return "ok";
    }
}

以上就是“vue+element-ui+axios多文件上傳怎么實(shí)現(xiàn)并顯示整體進(jìn)度”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI