Vue上传文件:ElementUI中的upload实现

摘要:
数据()需要由代理转发,否则将出现跨域问题:数据、附加到上载的附加参数和对象类型。IsBMP){this.common.errorTip('上传的图片必须是JPG/GIF/PNG/BMP格式!IsLt2M){this.common.errorTip(“上传的图片不能超过2MB!”);}return&&isLt2M;},3.如何同时传输表单和多个上传文件?newSubmitForm(){this.$refs['newform'].validate((有效)=˃{if(有效){//表单this.uploadForm.append('expName',this.newform.expName)this.uploadForm.apped('expSn',this.newform.expSn)this.uploadForm.aappend('groupId',this.newgroupId)this.uploadForm.append('subGroupId',this.newgroupId')this.uploadForm.append)newExp(this.uploadForm)。然后(res=˃{if(res.code===400){this.$message.error(res.error)}elseif(res.code===200){this.$message.success('上传成功!

一、上传文件实现

  两种实现方式:

1、直接action

<el-upload
  class="upload-file"
  drag
  :action="doUpload"
  :data="pppss">
  <i class="el-icon-upload"></i>
  <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</el-upload>

  :action,必选参数,上传的地址,String类型。data()需要使用代理转发,要不然会有跨域的问题

  :data,上传时附带的额外参数,object类型。用于传递其他的需要携带的参数,比如下面的srid

data(){
    return {
        ,doUpload:'/api/up/file'
        ,pppss:{
            srid:''
        }
    }
},

2、利用before-upload属性

  此种方式有个弊端,就是action是必选的参数,那么action如果和post的url一致,总会请求2次,所以一般把action随便写一个url,虽然不影响最终效果,但是这样会在控制台总有404错误报出

<el-upload
  class="upload-file"
  drag
  :action="doUpload"
  :before-upload="beforeUpload"
  ref="newupload"
  multiple
  :auto-upload="false">
  <i class="el-icon-upload"></i>
  <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
</el-upload>
beforeUpload(file){
    let fd = new FormData();
    fd.append('file',file);//传文件
    fd.append('srid',this.aqForm.srid);//传其他参数
    axios.post('/api/up/file',fd).then(function(res){
            alert('成功');
    })
},
newSubmitForm(){//确定上传
    this.$refs.newupload.submit();
}

二、常用方法介绍

1、动态改变action地址

  action是一个必填参数,且其类型为string,我们把action写成:action,然后后面跟着一个方法名,调用方法,返回你想要的地址,实现动态的去修改上传地址

//html 代码
<el-upload  :action="UploadUrl()"  :on-success="UploadSuccess" :file-list="fileList">
    <el-button size="small" type="primary" >点击上传</el-button>
</el-upload>

// js 代码在 methods中写入需要调用的方法
methods:{
    UploadUrl:function(){
        return "返回需要上传的地址";     
    }   
}   

2、在文件上传前做类型大小等限制

(1)一种方式是,加accpet属性

<el-upload class="upload-demo" :multiple="true" :action="action" accept="image/jpeg,image/gif,image/png,image/bmp" 
:file-list="fileList" :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">

(2)另一种方式是在上传前的触发函数里面去判断

beforeAvatarUpload(file) {
    const isJPG = file.type === 'image/jpeg';
    const isGIF = file.type === 'image/gif';
    const isPNG = file.type === 'image/png';
    const isBMP = file.type === 'image/bmp';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG && !isGIF && !isPNG && !isBMP) {
        this.common.errorTip('上传图片必须是JPG/GIF/PNG/BMP 格式!');
    }
    if (!isLt2M) {
        this.common.errorTip('上传图片大小不能超过 2MB!');
    }
    return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
},

3、同时传递form表单及有多个upload文件该如何传递

newSubmitForm () {
  this.$refs['newform'].validate((valid) => {
    if (valid) {
      //表单的数据
      this.uploadForm.append('expName', this.newform.expName)
      this.uploadForm.append('expSn', this.newform.expSn)
      this.uploadForm.append('groupId', this.newgroupId)
      this.uploadForm.append('subGroupId', this.newsubgroupId)
      this.uploadForm.append('expvmDifficulty', this.newform.expvmDifficulty)
      
      newExp(this.uploadForm).then(res => {
        if (res.code === 400) {
          this.$message.error(res.error)
        } else if (res.code === 200) {
          this.$message.success('上传成功!')
        
        }
      })
      this.$refs.uploadhtml.submit()   // 提交时分别触发各上传组件的before-upload函数
      this.$refs.uploadfile.submit()
      this.$refs.uploadvideo.submit()   
    } else {
      console.log('error submit!!')
      return false
    }
  })
},
newHtml (file) {   // before-upload
  this.uploadForm.append('html', file)
  return false
},
newFiles (file) {
  this.uploadForm.append('file[]', file)
  return false
},
newVideo (file) {
  this.uploadForm.append('video', file)
  return false
}
export function newExp (data) {
  return axios({
    method: 'post',  // 方式一定是post
    url: '你的后台接收函数路径',
    timeout: 20000,
    data: data        // 参数需要是单一的formData形式
  })
}

  注意:(1)对于多个上传组件来说,需要分别触发,去给FormData append数据

  (2)接收多文件一定要是数组形式的file[],this.uploadForm.append('file[]', file)

4、如何传递文件和其他参数

  就像第一节那样,如果不使用action实现上传,而使用before-upload属性也能实现上传的效果。

  before-upload属性,这是一个function类型的属性,默认参数是当前文件,只要能传递这个文件也能实现效果

  要传递这个方法就需要new一个formdata对象,然后对这个对象追加key和value,类似于postman测试时那样。

  另外注意:传递formdata和data不能一起传递,要传递formdata就不能有data,所以对于其他参数的传递,也要改为

beforeUpload (file,id) {
    let fd = new FormData()
    fd.append('file', file)
    fd.append('id',id)//其他参数
    axios.post(url, fd, {
         
    })
 },

  而不能使用这种又有FormData,又有data的模式

beforeUpload (file,id) {
        let fd = new FormData()
        fd.append('key', file, fileName)
        axios.post(url, fd,{
          data:{
           id:id
          },
          headers: {
           'Content-Type': 'multipart/form-data'
          }
        })
     },

 

免责声明:文章转载自《Vue上传文件:ElementUI中的upload实现》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇服务器端Session和客户端Session(和Cookie区别)Oracle--计算某一日期为一年中的第几周下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Vue中引入TradingView制作K线图

**前言: 本文使用的是1.10版本 , 可通过TradingView.version()查看当前版本. 附上开发文档地址:https://zlq4863947.gitbooks.i...** 一、修改datafeed.js为export导出,并在vue文件引入TradingView内部代码charting_library.min.js和datafeed....

5款vue前端UI框架

Vue.js是一套构建用户界面的 渐进式框架。与其他重量级框架不同的是,Vue 采用自底向上增量开发的设计。 实用的 Vue.js组件库可以帮助我们快速搭建页面,下面介绍小编认为比较受欢迎的五个vue前端ui框架。 TOP5——Vue-Blu Vue-Blu是基于Vuejs和Bulma开发的开源UI组件库。旨在为PC端的前端开发(特别是中后台产品)提供一...

Vue搭建脚手架2

Vue2.0搭建Vue脚手架(vue-cli) 在网上找了很多的搭建脚手架教程,但都不求甚解。终于找到2个比较好的教程,读者可对比阅读1和2,在这里分享给大家,希望对初学者有所帮助。ps:高手请绕道。 1.使用npm全局安装vue-cli(前提是你已经安装了nodejs,否则你连npm都用不了),在cmd中输入一下命令 npm install --glo...

vue 中的 .sync 修饰符 与 this.$emit('update:key', value)

vue 中 .sync 修饰符,是 2.3.0+ 版本新增的功能 在有些情况下,我们可能需要对一个 prop 进行“双向绑定”。不幸的是,真正的双向绑定会带来维护上的问题,因为子组件可以变更父组件,且在父组件和子组件两侧都没有明显的变更来源。 这也是为什么我们推荐以update:myPropName的模式触发事件取而代之。举个例子,在一个包含titlepr...

【Vue后台管理三】集成echarts图表

集成echarts图标 路一步步走,代码得一个个敲,今天自己来集成了echarts图标,为什么要集成echarts了? 图表表示数据,应该是最清晰直白了,所以很多管理页面的首页都集成了。 首先看看效果 下面应该还有一个关于每月销量收入的图表,明天在加上。 站在巨人的肩膀上 我个人没真实做过后台管理项目,所以了这些后台的样子,是参考我公司后台管理样式和一些...

学习vue 20天,我写了点东西

往昔 最初团队里使用Angularjs进行开发,刚开始还好,到了项目后期越发感觉Angularjs太重了,以至于后来重构项目时,毅然放弃Angularjs,投入了Vue的怀抱。除了组建团队时,是我搭建了基于Angularjs的前端开发框架,之后都是由前端小组开发。前段时间,由于公司层面的原因,整个团队解散,不得已我又要写前端程序了。 虽然前期Angular...