Javascript

element-ui多文件上传的实现示例

本文主要是介绍element-ui多文件上传的实现示例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

上传方案一:

先将文件上传到七牛,再将七牛上传返回的文件访问路径上传到服务器

<div class="upload-music-container">
  <el-upload
   class="upload-music"
   ref="upload"
   action="http://up-z2.qiniup.com/"
   :data="{token:uploadToken}"
   multiple
   accept=".mp3"
   :before-upload="uploadBefore"
   :on-change="uploadChange"
   :on-success="uploadSuccess"
   :on-error="uploadError">
   <el-button size="small" type="primary">选取文件</el-button>
   <div slot="tip" class="el-upload__tip">仅支持上传mp3文件,文件大小不超过500M</div>
  </el-upload>
  <el-button size="small" type="success" @click="submitUpload">上传到服务器</el-button>
</div>
 

export default {
  name: 'uploadMusic',
  data() {
   return {
    headers: {},
    uploadToken: null,
    canUploadMore: true,
    fileList: null,
   }
  },
  created() {
   this.headers = {}   //此处需要与server约定具体的header
   this.getUploadToken()
  },
  methods: {
   //获取上传七牛token凭证
   getUploadToken() {
    this.$http.get('xxxxxxx', {headers: this.headers}).then(response => {
     if (response.data.status == 200) {
      let resp = response.data.data
      this.uploadToken = resp.token
     } else {
      this.$message({
       message: '获取凭证失败,请重试',
       type: 'error'
      })
     }
    })
   },
   //获取音频文件时长
   getVideoPlayTime(file, fileList) {
    let self = this
    //获取录音时长
    try {
     let url = URL.createObjectURL(file.raw);
     //经测试,发现audio也可获取视频的时长
     let audioElement = new Audio(url);
     let duration;
     audioElement.addEventListener("loadedmetadata", function (_event) {
      duration = audioElement.duration;
      file.duration = duration
      self.fileList = fileList
     });
    } catch (e) {
     console.log(e)
    }
   },
   //校验上传文件大小
   uploadChange(file, fileList) {
    this.fileList = fileList
    let totalSize = 0
    for (let file of fileList) {
     totalSize += file.raw.size
    }
    if (totalSize > 500 * 1024 * 1024) {
     this.canUploadMore = false
     this.$message({
      message: '上传文件不能不超过500M',
      type: 'warn'
     })
    } else {
     this.canUploadMore = true
    }
   },
   uploadBefore(file) {
    if (this.canUploadMore) {
     return true
    }
    return false
   },
   //上传成功
   uploadSuccess(response, file, fileList) {
    this.getVideoPlayTime(file, fileList)
   },
   //上传失败
   uploadError(err, file, fileList) {
    console.log(err)
   },
   //上传服务器数据格式化
   getUploadMusicList() {
    let musicList = []
    for (let file of this.fileList) {
     if (file.response && file.response.key) {
      musicList.push({
       "play_time": file.duration, //播放时长
       "size": file.size/1024,   //文件大小 单位 kb
       "song_name": file.name,   //歌曲名
       "voice_url": "xxxx"     //上传七牛返回的访问路径
      })
     }
    }
    return musicList
   },
   //上传至服务器
   submitUpload() {
    let musicList = this.getUploadMusicList()
    this.$http.post('xxxxxxxxxx', {music_list: musicList}, {headers: this.headers}).then(response => {
     if (response.data.status == 200) {
      this.$refs.upload.clearFiles() //上传成功后清空文件列表
      this.$message({
       message: '上传服务器成功',
       type: 'success'
      })
     } else{
      this.$message({
       message: '上传服务器失败,请重试',
       type: 'error'
      })
     }
    }).catch(err => {
     this.$message({
      message: '上传服务器失败,请重试',
      type: 'error'
     })
    })
   },
  }
 }

上传方案二:

直接将文件上传到服务器

<div class="upload-music-container">
  <el-upload
   class="upload-music"
   ref="upload"
   multiple
   action=""
   :auto-upload="false"
   :http-request="uploadFile">
   <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
   <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
   <div slot="tip" class="el-upload__tip">只能上传mp3文件,且单次不超过500M</div>
  </el-upload>
</div>

export default {
  name: 'uploadMusic',
  data() {
   return {
    fileType:'video',
    fileData: new FormData(),
    headers:{},
   }
  },

补充:element-ui实现多文件加表单参数上传

element-ui是分图片多次上传,一次上传一个图片。

如果想一次上传多个图片,就得关掉自动上传:auto-upload=‘false',同时不使用element内置上传函数,换成自己写的onsubmit()

为了实现图片的添加删除,可在on-change与on-remove事件中取得filelist(filelist实质就是uploadFiles的别名,而uploadFiles就是element内置的用于保存待上传文件或图片的数组),在最后一步提交的过程中,将filelist中的值一一添加到formdata对象中(formdata.append()添加,formdata.delete()删除),然后统一上传。

ps:on-preview事件和<el-dialog>组件以及对应属性、方法这一体系是用来实现图片的点击放大功能。被注释掉的beforeupload只有一个实参,是针对单一文件上传时使用到的,这里无法用上

<template>
 <div>
  <el-upload
   action="http://127.0.0.1:8000/api/UploadFile/"
   list-type="picture-card"
   :auto-upload="false"
   :on-change="OnChange"
   :on-remove="OnRemove"
   :on-preview="handlePictureCardPreview"
   :before-remove="beforeRemove"
   >
   <i class="el-icon-plus"></i>
  </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 {host,batchTagInfo} from '../../api/api'
export default {
  data() {
   return {
    param: new FormData(),
    form:{},
    count:0,
    fileList:[],
    dialogVisible:false,
    dialogImageUrl:''
   };
  },
  methods: {
   handlePictureCardPreview(file) {
    this.dialogImageUrl = file.url;
    this.dialogVisible = true;
   },
   beforeRemove(file, fileList) {
    return this.$confirm(`确定移除 ${ file.name }?`);
   },
   OnChange(file,fileList){
    this.fileList=fileList
 
   },
   OnRemove(file,fileList){
    this.fileList=fileList
   },
   //阻止upload的自己上传,进行再操作
   // beforeupload(file) {
   //   console.log('-------------------------')
   //   console.log(file);
   //   //创建临时的路径来展示图片
   //   //重新写一个表单上传的方法
   //   this.param = new FormData();
   //   this.param.append('file[]', file, file.name);
   //   this.form={
   //    a:1,
   //    b:2,
   //    c:3
   //   }
   //   // this.param.append('file[]', file, file.name);
   //   this.param.append('form',form)
   //   return true;
   // },
   fun(){
    console.log('------------------------')
    console.log(this.fileList)
   },
   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.fileList.length;i++){
     file='file'+this.count
     this.count++
     this.param.append(file,this.fileList[i].raw)
    }
    batchTagInfo(this.param) 
     .then(res=>{
      alert(res)
     })
   }
  }
 }
</script>
<style> 
</style>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持找一找教程网。

这篇关于element-ui多文件上传的实现示例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!