一、上传文件实现

  两种实现方式:

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'
          }
        })
     },

DEMO下载地址:https://dwz.cn/fgXtRtnu

Vue上传文件:ElementUI中的upload实现的更多相关文章

  1. vue 上传文件 和 下载文件

    Vue上传文件,不必使用什么element 的uplaod, 也不用什么npm上找的个人写的包,就用原生的Vue加axios就行了, 废话不多说,直接上代码:html: <input type= ...

  2. vue 上传文件 和 下载文件 面试的时候被问到过

    Vue上传文件,不必使用什么element 的uplaod, 也不用什么npm上找的个人写的包,就用原生的Vue加axios就行了, 废话不多说,直接上代码:html: <input type= ...

  3. axios+Vue上传文件显示进度

    一,前言 最近在用Vue,然后上传文件时需要显示进度,于是网上搜了一下,经过自己实测终于也弄明白了 二,效果 三,代码 HTML代码 <div id="app"> &l ...

  4. vue上传文件

    <div> <input type="file" class="file" name="file" @change=&qu ...

  5. vue+上传文件夹

    在做项目开发的时候,上传东西无论文件也好,还是文件夹都需要用到 <input type="file" id="filepicker" name=" ...

  6. vue 上传文件 并以表格形式显示在页面上

    先上代码 <label for="file" class="btn">多文件上传</label> <input type=&quo ...

  7. spring boot上传文件错误The temporary upload location [/tmp/tomcat.5260880110861696164.8090/work/Tomcat/localhost/ROOT] is not valid

    参考了:https://www.jianshu.com/p/cfbbc0bb0b84 再次感谢,但还是有些调整 一.在zuul服务中加入两个配置参数(location: /data/apps/temp ...

  8. 工作笔记——限定input上传文件对话框中能选取的文件的格式

    原文:http://www.dengzhr.com/frontend/1059 input[file]标签的accept属性可用于指定上传文件的 MIME类型 . 例如,想要实现默认上传图片文件的代码 ...

  9. SVN上传文件过程中出现错误“不知道这样的主机”

    在虚拟机中安装完成VisualSVN Server,并且在本地客户端也安装好了TortoiseSVN,在上传文件到服务器的过程中出现错误“不知道这样的主机”,如下图: 地址https://admin- ...

随机推荐

  1. utils.js和vue-loader.conf.js

    var utils = require('./utils')var config = require('../config')var isProduction = process.env.NODE_E ...

  2. node.js中事件触发器events的使用

    node.js是基于事件驱动的,通过events,我们可以方便的创建事件,并通过触发事件来调用我们自定义的监听函数. 所有能触发事件的对象都应该是 EventEmitter 类的实例,一般我们自定义一 ...

  3. Logback报错 no applicable action for [Encoding], current ElementPath is [[configuration][appender][Encoding]]

    老版本是0.9,移到springboot项目,解决办法,删除xml配置文件节点<Encoding>UTF-8</Encoding>

  4. 前端基础之JavaScript day51

    前端基础之JavaScript   JavaScript概述 JavaScript的历史 1992年Nombas开发出C-minus-minus(C--)的嵌入式脚本语言(最初绑定在CEnvi软件中) ...

  5. Linux locales

    一.简介   二.语法   三.实例 aptitude install locales dpkg-reconfigure locales ; vi /etc/default/locale more / ...

  6. 7.Mysql存储引擎

    7.表类型(存储引擎)的选择7.1 Mysql存储引擎概述 mysql支持插件式存储引擎,即存储引擎以插件形式存在于mysql库中. mysql支持的存储引擎包括:MyISAM.InnoDB.BDB. ...

  7. PAT 1068 万绿丛中一点红(20)(测试点分析+思路分析)

    1068 万绿丛中一点红(20 分) 对于计算机而言,颜色不过是像素点对应的一个 24 位的数值.现给定一幅分辨率为 M×N 的画,要求你找出万绿丛中的一点红,即有独一无二颜色的那个像素点,并且该点的 ...

  8. BZOJ1855 股票交易 单调队列优化 DP

    描述 某位蒟佬要买股票, 他神奇地能够预测接下来 T 天的 每天的股票购买价格 ap, 股票出售价格 bp, 以及某日购买股票的上限 as,  某日出售股票上限 bs, 并且每次股票交 ♂ 易 ( 购 ...

  9. 201621123008 《Java程序设计》第八周学习总结

    1. 本周学习总结 2. 书面作业 1. ArrayList代码分析 1.1 解释ArrayList的contains源代码 源代码: public boolean contains(Object o ...

  10. 网页定时器setTimeout( )

    不斷重複執行的 setTimeout( ) setTimeout( ) 預設只是執行一次, 但我們可以使用一個循環方式, 使到一個setTimeout( ) 再啟動自己一次, 就會使到第二個 setT ...