vue+element-ui+axios多文件上傳的實(shí)現(xiàn)并顯示整體進(jìn)度
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 style="width: 100%;"
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文件,且不超過(guò)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ǔ)起來(lái)(給后臺(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ǔ)起來(lái)(給后臺(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多文件上傳的問(wèn)題
業(yè)務(wù)場(chǎng)景
在使用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文件,且不超過(guò)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è)文件的話 后端接口寫(xiě) Multipart file
// 多個(gè)文件的話 后端接口寫(xiě) 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";
}
}以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- vue+axios實(shí)現(xiàn)文件上傳的實(shí)時(shí)進(jìn)度條
- axios進(jìn)度條onDownloadProgress函數(shù)total參數(shù)undefined解決分析
- Vue+Axios實(shí)現(xiàn)文件上傳自定義進(jìn)度條
- axios實(shí)現(xiàn)文件上傳并獲取進(jìn)度
- axios+Vue實(shí)現(xiàn)上傳文件顯示進(jìn)度功能
- 使用axios實(shí)現(xiàn)上傳圖片進(jìn)度條功能
- vue使用axios實(shí)現(xiàn)文件上傳進(jìn)度的實(shí)時(shí)更新詳解
- javascript axios 實(shí)現(xiàn)進(jìn)度監(jiān)控的示例代碼
相關(guān)文章
vue實(shí)現(xiàn)鼠標(biāo)移過(guò)出現(xiàn)下拉二級(jí)菜單功能
這篇文章主要介紹了vue實(shí)現(xiàn)鼠標(biāo)移過(guò)出現(xiàn)下拉二級(jí)菜單功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12
vscode中開(kāi)發(fā)運(yùn)行uniapp項(xiàng)目詳細(xì)步驟
VSCode作為一個(gè)非常強(qiáng)大的代碼編輯器,可以集成眾多的插件和工具來(lái)優(yōu)化開(kāi)發(fā)效率,這篇文章主要給大家介紹了關(guān)于vscode中開(kāi)發(fā)運(yùn)行uniapp項(xiàng)目的詳細(xì)步驟,需要的朋友可以參考下2023-07-07
用npm安裝vue和vue-cli,并使用webpack創(chuàng)建項(xiàng)目的方法
今天小編就為大家分享一篇用npm安裝vue和vue-cli,并使用webpack創(chuàng)建項(xiàng)目的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-09-09
詳解TypeScript+Vue 插件 vue-class-component的使用總結(jié)
這篇文章主要介紹了TypeScript+Vue 插件 vue-class-component的使用總結(jié),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-02-02
詳解Vue-cli 創(chuàng)建的項(xiàng)目如何跨域請(qǐng)求
本篇文章主要介紹了詳解Vue-cli 創(chuàng)建的項(xiàng)目如何跨域請(qǐng)求 ,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05
vue.js 實(shí)現(xiàn)圖片本地預(yù)覽 裁剪 壓縮 上傳功能
這篇文章主要介紹了vue.js 實(shí)現(xiàn)圖片本地預(yù)覽裁剪壓縮上傳功能,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2018-03-03
Vue中keyup.enter和blur事件沖突的問(wèn)題及解決
這篇文章主要介紹了Vue中keyup.enter和blur事件沖突的問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10
Vue3+Tsx給路由加切換動(dòng)畫(huà)時(shí)的踩坑及解決
這篇文章主要介紹了Vue3+Tsx給路由加切換動(dòng)畫(huà)時(shí)的踩坑及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01

