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

所属分类: 网络编程 / JavaScript 阅读数: 286
收藏 0 赞 0 分享

上传方案一:

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

<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>

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

更多精彩内容其他人还在看

jQuery LigerUI 使用教程表格篇(1)

ligerGrid是ligerui系列插件的核心控件,用户可以快速地创建一个美观,而且功能强大的表格,支持排序、分页、多表头、固定列等等
收藏 0 赞 0 分享

JavaScript中常用的运算符小结

JavaScript中常用的运算符小结,需要的朋友可以参考下。
收藏 0 赞 0 分享

深入理解JavaScript系列(13) This? Yes,this!

在这篇文章里,我们将讨论跟执行上下文直接相关的更多细节。讨论的主题就是this关键字。实践证明,这个主题很难,在不同执行上下文中this的确定经常会发生问题
收藏 0 赞 0 分享

javascript (用setTimeout而非setInterval)

javascript (用setTimeout而非setInterval)如果用setInterval 可能出现 下次调用会在前一次调用前调用
收藏 0 赞 0 分享

JavaScript中两个感叹号的作用说明

用两个感叹号的作用就在于,如果明确设置了o中flag的值(非null/undefined/0""/等值),自然test就会取跟o.flag一样的值;如果没有设置,test就会默认为false,而不是null或undefined
收藏 0 赞 0 分享

javascript写的简单的计算器,内容很多,方法实用,推荐

最近用javascript写了一个简单的计算器,自己测试感觉还好,代码都给了注释,非常不错,推荐大家学习。
收藏 0 赞 0 分享

js的表单操作 简单计算器

javascript写的简单的加减乘除计算器,里面涉及到一些方法还是很实用的哦,新手不要错过
收藏 0 赞 0 分享

Jquery中删除元素的实现代码

empty用来删除指定元素的子元素,remove用来删除元素,或者设定细化条件执行删除
收藏 0 赞 0 分享

javaScript 利用闭包模拟对象的私有属性

JavaScript缺少块级作用域,没有private修饰符,但它具有函数作用域。作用域的好处是内部函数可以访问它们的外部函数的参数和变量(除了this和argument
收藏 0 赞 0 分享

为JavaScript类型增加方法的实现代码(增加功能)

大家在js开发过程中有些功能已经满足不了我们的需求,或没有我们需要的功能,那么我们就可以自己扩展下,个性化js
收藏 0 赞 0 分享
查看更多