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

一、上传文件实现

  两种实现方式:

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

原文地址:https://www.cnblogs.com/goloving/p/8967865.html

时间: 2024-08-02 21:53:09

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

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

先上代码 <label for="file" class="btn">多文件上传</label> <input type="file" style="display:none;" id="file" multiple @change="file()"> 这是上传文件的按钮 <table> <tr> <th class=&q

vue 上传文件示例

1 <template> 2 <div id="app"> 3 <input type="file" ref="upload"> 4 <button @click="uploadHandle">点击上传</button> 5 </div> 6 7 </template> 8 9 <script> 10 11 export defau

springMVC+spring+hibernate注解上传文件到数据库,下载,多文件上传

数据库 CREATE TABLE `annex` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `realName` varchar(36) DEFAULT NULL, `fileContent` mediumblob, `handId` bigint(20) DEFAULT NULL, `customerId` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`), KEY `fk_id` (`handId`), CON

文件上传表单 上传文件的细节 文件上传下载和数据库结合

1 文件上传表单   1)上传文件的本质是文本复制的过程   2)技术层面,在Java中一定会用到IO操作,主要以二进制方式读写   3)传统方式下,对于上传文件字段不同的浏览器有着不同的解析方式,例如:     IE6:upfile=c:\aa\bb\a.JPG     非IE6: upfile=a.JPG   4)可以将form以MIME协议的方式将上传文件传递到服务端,服务端以二进制流的方式读写     代码:客户端form enctype="multipart/form-data&quo

Android开发笔记(一百一十)使用http框架上传文件

HTTP上传 与文件下载相比,文件上传的场合不是很多,通常用于上传用户头像.朋友圈发布图片/视频动态等等,而且上传文件需要服务器配合,所以容易被app开发者忽略.就上传的形式来说,app一般采用http上传文件,很少用ftp上传文件. HttpURLConnection上传 很可惜Android没有提供专门的文件上传工具类,所以我们要自己写代码实现上传功能了.其实也不难,一样是按照普通网络访问的POST流程,只是要采用"multipart/form-data"方式来分段传输.另外文件上

webpy上传文件

上传文件 保存上传的文件 上传文件 import web urls = ( '/upload', 'Upload', ) class Upload: def GET(self): return """<html><head></head><body> <form method="POST" enctype="multipart/form-data" action="&quo

使用uploadify组件上传文件

uploadify是和jQuery结合使用的异步上传组件,主要功能是批量上传文件,使用多线程来上传多个组件. 下载并导入js和样式文件 在正式学习uploadify组件之前,首先就是去官网下载最新的js和css等. http://www.uploadify.com/download/ 解压后如图:上面使用红色标示的文件是需要引入到项目中的.另外别忘了引入jquery.js文件 html页面以及上传条件的编写 <html> <head> <base href="<

Hessian学习总结(二)——使用hessian上传文件

hessian较早版本通过 byte[] 进行文件传输:4.0之后支持 InputStream 作为参数或返回值进行传输. 注意:hessian会读取整个文件,如果文件过大,会导致JVM内存溢出.可以通过控制上传文件的大小,设置合理的JVM参数,以及采用随机读取方式来解决. 一.创建Hessian服务端 创建一个FileUploader Web项目作为文件上传的服务端,如下图所示: 1. 1.创建文件上传服务接口FileUploadServiceI FileUploadServiceI接口代码如

利用Struts上传文件

在利用struts2完成上传文件到服务器时,遇到获取不到文件名 原因是在Action中的属性名没有和jsp中的属性名匹配 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"