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


Posted in Javascript onApril 10, 2019

上传方案一:

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

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

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

Javascript 相关文章推荐
jquery 注意事项与常用语法小结
Jun 07 Javascript
JavaScript面向对象(极简主义法minimalist approach)
Jul 17 Javascript
javaScript让文本框内的最后一个文字的后面获得焦点实现代码
Jan 06 Javascript
JS中不为人知的五种声明Number的方式简要概述
Feb 22 Javascript
JavaScript二维数组实现的省市联动菜单
May 08 Javascript
js实现接收表单的值并将值拼在表单action后面的方法
Nov 23 Javascript
javascript input输入框模糊提示功能的实现
Sep 25 Javascript
微信小程序 this.triggerEvent()的具体使用
Dec 10 Javascript
Vue + Scss 动态切换主题颜色实现换肤的示例代码
Apr 27 Javascript
从零开始用webpack构建一个vue3.0项目工程的实现
Sep 24 Javascript
解决Vue项目中tff报错的问题
Oct 21 Javascript
解决vscode进行vue格式化,会自动补分号和双引号的问题
Oct 26 Javascript
基于mpvue搭建微信小程序项目框架的教程详解
Apr 10 #Javascript
Webpack4+Babel7+ES6兼容IE8的实现
Apr 10 #Javascript
微信小程序第三方框架对比 之 wepy / mpvue / taro
Apr 10 #Javascript
用node撸一个监测复联4开售短信提醒的实现代码
Apr 10 #Javascript
从0到1搭建Element的后台框架的方法步骤
Apr 10 #Javascript
详解vue.js移动端配置flexible.js及注意事项
Apr 10 #Javascript
小程序分享模块超级详解(推荐)
Apr 10 #Javascript
You might like
php下使用无限生命期Session的方法
2007/03/16 PHP
解析:使用php mongodb扩展时 需要注意的事项
2013/06/18 PHP
php生成xml时添加CDATA标签的方法
2014/10/17 PHP
PHP使用array_fill定义多维数组的方法
2015/03/18 PHP
javascript动画对象支持加速、减速、缓入、缓出的实现代码
2012/09/30 Javascript
chrome下jq width()方法取值为0的解决方法
2014/05/26 Javascript
jquery通过load获取文件的内容并跳到锚点的方法
2015/01/29 Javascript
浅谈JavaScript的事件
2015/02/27 Javascript
js电话号码验证方法
2015/09/28 Javascript
微信小程序排坑指南详解
2018/05/23 Javascript
vue父组件异步获取数据传给子组件的方法
2018/07/26 Javascript
Bootstrap4 gulp 配置详解
2019/01/06 Javascript
JS实现的杨辉三角【帕斯卡三角形】算法示例
2019/02/26 Javascript
微信小程序实现的五星评价功能示例
2019/04/25 Javascript
JavaScript获取时区实现过程解析
2020/09/24 Javascript
Python Deque 模块使用详解
2014/07/04 Python
简单介绍Python中的try和finally和with方法
2015/05/05 Python
利用Python实现图书超期提醒
2016/08/02 Python
Python 模拟生成动态产生验证码图片的方法
2020/02/01 Python
Django生成数据库及添加用户报错解决方案
2020/10/09 Python
使用CSS3和Checkbox实现JQuery的一些效果
2015/08/03 HTML / CSS
html2 canvas生成清晰的图片实现打印功能
2019/09/23 HTML / CSS
英国最大的海报商店:GB Posters
2018/03/20 全球购物
婴儿地球:Baby Earth
2018/12/25 全球购物
什么是.net
2015/08/03 面试题
预备党员思想汇报
2014/01/08 职场文书
个人作风剖析材料
2014/02/02 职场文书
精神文明建设先进工作者事迹材料
2014/05/02 职场文书
乡镇群众路线教育实践活动整改措施
2014/10/04 职场文书
党员个人批评与自我批评
2014/10/14 职场文书
护士年终考核评语
2014/12/31 职场文书
教师个人学习总结
2015/02/11 职场文书
学生会个人总结范文
2015/02/15 职场文书
婚宴致辞
2015/07/28 职场文书
2016廉洁从业学习心得体会
2016/01/19 职场文书
六五普法学习心得体会
2016/01/21 职场文书