您好,登錄后才能下訂單哦!
今天小編給大家分享一下vue+element-ui+axios多文件上傳怎么實現并顯示整體進度的相關知識點,內容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。
element-ui自帶的多文件上傳是做成了多文件多次上傳,公司有需求需要選取多個文件一次上傳全部.
代碼部分
<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>點擊上傳</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">上傳到服務器</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: {} // 上傳文件主要參數 } }, methods: { submitUpload () { if (this.fileList.length < 1) { this.$message.warning('請選擇文件!') return false } this.$refs.uploadMul.submit() if (this.param instanceof FormData) { // 附加參數 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:被上傳文件的總大小 // 進度條 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}!`) // 每移除一個文件,param重新賦值 this.param = new FormData() this.fileList = [...fileList] this.fileList.forEach((file, index) => { this.param.append(`file`, file.raw) // 把單個文件重命名,存儲起來(給后臺) }) }, 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) // 把單個文件重命名,存儲起來(給后臺) }) }, // 超出上傳個數時調用 uploadLimit (files, fileList) { this.$message.error(`最多允許同時上傳${this.maxUploadSize}個文件!`) // files.forEach((file, index) => { // console.log(index) // }) }, beforeUpload (file) { }, uploadFile (file) { // 該方法需存在,防止空action時element-ui報404異常 }, clearFiles () { this.fileList = [] this.param = {} this.$refs.uploadMul.clearFiles() }, // 初始化表單數據 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); }
在使用vue+elementui 實現文件上傳的時候,我發現官網給的組件每次都會自動上傳,而且一次上傳一個文件。但是我實際的業務是,一次上傳多個文件。
前端代碼:
<template> <div> <!-- 文件上傳組件--> <!-- :auto-upload="false" 這里設置為不自動上傳 ,所以: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">點擊查看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 // 單個文件的話 后端接口寫 Multipart file // 多個文件的話 后端接口寫 Multipart [] files // 文件名需要對應 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多文件上傳怎么實現并顯示整體進度”這篇文章的所有內容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。