【el】上传、导出

一、上传

1、上传多个文件(自动上传)

情况一:正常上传,没有限制

<el-upload
              class="upload-demo"
              action="#"
              ref="upload"
              multiple
              :file-list="fileList"
              :on-change="
                (file, fileList) => {
                  change(file, fileList, index);
                }
              "
              :auto-upload="false"
              :http-request="httprequest"
              :on-remove="remove"
              accept=".xlsx,.xls,.jpg,.jpeg,.gif,.png,.pdf,.doc,.docx"
            >
              <el-button
                slot="trigger"
                icon="el-icon-upload2"
                style="width: 100%; text-align: left"
                size="small"
                class="dashedbtn"
                >上传文件</el-button
              >
            </el-upload>

<script>
import { UploadData } from "@/api/Equipment";

export default {
  data() {
    return {
      tableFormrules: [],
      tableForm: {},
      ta: [],
      fileList: [], //文件列表
      formData: new FormData(),
      up: [],
      List:[]
    };
  },
  methods: {
    // 导入
    remove(file, fileList) {
      this.fileList = fileList;
      this.List = this.fileList.map((item, index) => {
            return item.FileUrl;
          });
    },
    change(file, fileList, index) {
      this.fileList = []; // 清空图片已经上传的图片列表(绑定在上传组件的file-list)
      let a = 0;
      fileList.forEach((item, idx) => {
        /*在此处,对比文件名,将文件名相同的对比次数累加,
      相同的文件名累加值为 2 时,说明文件名已经重复,直接删掉。*/
        if (file.name === item.name) {
          a++;
          // console.log(a, file, fileList);
          if (a === 2) {
            this.$mess.info("不能重复上传,已把重复文件删除");
            fileList.splice(idx, 1);
          }
        }
      });
      this.fileList = fileList;
      if (a !== 2) {
        this.httprequest(file, index);
      }
    },

    async httprequest(file, index) {
      // 一个一个上传
      var formData = new FormData();
      formData.append("files", file.raw);
      const res = await UploadData(formData);
      // console.log(res, "123");
      if (res.code === 200) {
        const a = [];
        a.push(res.data[0].FileUrl);
        //赋值
        this.List = a;
        this.$mess.success("上传成功"); //这个是封装的,无论调用多少次,都只显示一次
      }
    },
  },
};
</script>

情况二:上传前判断文件大小,超过100则不上传

<el-upload
                  class="upload-demo"
                  ref="upload"
                  action
                  multiple
                  :file-list="upList"
                  :show-file-list="false"
                  :on-change="changeA"
                  accept=".png,.jpg,.pdf,.docx,.xlsx,.opju,.Dwg,.dxf,.dws,.dwt"
                >
                  <el-button
                    slot="trigger"
                    type="text"
                    size="small"
                  >
                      <img src="@/assets/upload.png" width="25px" />
                  </el-button>
                </el-upload>
changeA(file, fileList) {
       const issize = file.file.size / 1024 / 1024 > 100;
       if (issize) {
         this.uploadNum++;
         // this.$message.error(file.file.name + "文件超过100M,请重新上传。");
       } else {
       this.http(file);
       this.upList.unshift(file);
       }
    },
    async http(file) {
      this.treeloading = true;//加载中提示,是加在表单中的
      var formData = new FormData();
      formData.append("files", file.file);
      formData.append("storageAddress", this.pas); //携带其他参数
      const res = await uploadFileDev(formData);
      if (res.code === 200) {
        // this.$mess.success("上传成功"); //这个是封装的,无论调用多少次,都只显示一次
        if (res.data.length > 0) {
          this.treeData.path = res.data[0].fileDownloadPath;
          this.treeData.lable = res.data[0].fileName;
        }
        const req = await AddBpmFile({
          id: "",
          dataid: this.Form.dataid,
          node_uuid: this.List.node_uuid,
          userid: this.userid,
          username: this.name,
          folderid: this.folderid,
          filename: this.treeData.lable,
          path: this.treeData.path,
        });
        if (req.code === 200) {
          this.ind++;//是否是所有文件都上传成功了,是,则调用接口刷新页面
          if (this.ind === this.upList.length) {
            this.$emit("GetFromData", this.Form.dataid);
             if (this.uploadNum > 0) {
               this.$mess.success(
                 "添加附件成功,但本次上传有" +
                   this.uploadNum +
                   "个文件大小超过100M,已取消上传"
               );
             } else {
               this.$mess.success("添加附件成功");
             }
            this.ind = 0;
            this.upList = [];
            this.uploadNum = 0;
            this.treeloading = false;
            this.$forceUpdate();
          }
        } else {
          this.treeloading = false;
          this.$mess.error(req.data);
        }
      } else {
        this.treeloading = false;
        this.$mess.error(res.msg);
      }
    },

2、上传多个文件(手动上传)

     <el-upload
            class="upload-demo"
            action="#"
            ref="upload"
            multiple
            :auto-upload="false"
            :file-list="fileList"
            :on-change="
              (file, fileList) => {
                change(file, fileList);
              }
            "
            :on-remove="remove"
          >
            <div style="display: flex">
              <el-button slot="trigger" size="small" class="addbtn">上传文件</el-button>
              <div
                slot="tip"
                class="el-upload__tip"
                style="margin: auto 0; margin-left: 10px; color: #c0c4cc"
              >
                文件扩展名:.rar .zip .doc .docx .pdf .ipg...
              </div>
            </div>
          </el-upload>
<el-button slot="trigger" size="small" class="addsub">保存</el-button >

<script>
import { UploadData } from "@/api/Equipment";

export default {
  data() {
    return {
      form: {
        equipmentid: 0, //设备id
        filelist: [], //设备文件集合
      },
      fileList: [], //文件列表
      formData: new FormData(),
    };
  },
  methods: {
   // 保存
    async addsub() {
      if (this.fileList.length > 0) {
        this.http();
      }
      //其他操作
    },
      remove(file, fileList) {
      this.fileList = fileList;
      this.form.filelist = [];
      this.fileList.forEach((item, index) => {
        this.form.filelist.push({
          filename: item.name,
          fileurl: item.url,
        });
      });
      // console.log(this.fileList, this.form.filelist)
    },
    change(file, fileList) {
      this.fileList = []; // 清空图片已经上传的图片列表(绑定在上传组件的file-list)
      let a = 0;
      fileList.forEach((item, idx) => {
        if (file.name === item.name) {
          a++;
          if (a === 2) {
            this.$mess.info("不能重复上传,已把重复文件删除");
            fileList.splice(idx, 1);
          }
        }
      });
      this.fileList = fileList;
    },

    // 自定义上传
    async http(fileList) {
      this.fileList.forEach((file) => {
        this.formData.append("files", file.raw);
      });
      const res = await UploadData(this.formData);
      // console.log(res, "123");
      if (res.code === 200) {
        res.data.forEach((item, index) => {
          this.form.filelist.push({
            filename: item.FileName,
            fileurl: item.FileUrl,
          });
          this.fileList.push({
            name: item.FileName,
            url: item.FileUrl,
          });
        });
        this.$message.success("上传成功");
      }
    },
    },
  },
};
</script>

3、上传文件前先判断条件,再上传

需求:判断是否选中,如果没有选中则提示并不出现弹窗(我这里做的是树状单选)

第一步,给上传的按钮添加事件

             <el-upload
                  class="upload-demo"
                  ref="upload"
                  action=""
                  :show-file-list="false"
                  :limit="1"
                  :http-request="http"
                >
                  <el-button
                    slot="trigger"
                    size="small"
                    type="primary"
                    @click="before"
                    >选取文件</el-button
                  >
                </el-upload>

第二步:写js


methods: { 
   before(e) {
      if (!this.folderid) {
        this.$mess.error("请选择所需上传文件夹");
        e.stopPropagation(); // 阻止事件冒泡到父元素
      }
    },
 }

4、上传文件的同时携带其他参数

其他参数还是使用formData.append的方法添加,然后和文件一起传给后端
storageAddress就是后端的字段


async httpA(file) {
      var formDataA = new FormData();
      formDataA.append("files", file.file);
      let nu = this.pas + file.file.name;
      formData.append("storageAddress", nu); //携带其他参数
      const res = await uploadFileDev(formData);
      }

二、导出文件

  1. 下载文件(可能是文件也可能是图片)

调用后端的接口,接口返回的是文件流

先在接口处添加responseType: "blob",


// 通用文件下载
export function download(params) {
  return requestDEV({
    url: "/dev/file/download",
    method: "get",
    responseType: "blob",
    params,
  });
}

然后再页面使用


async nodeClick(data, node, item) {
      if (node.data.id) {
        const res = await download({ id: node.data.id });//接口

        const blob = new Blob([res]);
        const elink = document.createElement("a");
        elink.download = node.data.fileName;//文件名
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      }
    },

2、导出xlsx(这里直接调用接口获取文件地址,然后下载)


   // 导出
    AccountMb(data) {
      // window.open('/excel-mb.xlsx')
      const link = document.createElement("a");
      link.style.display = "none";
      link.href = data; //下载地址
      const fileName = "设备.xlsx";//文件名称
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
    },
   //导出按钮
    async daochu() {
      const res = await ExportEquipment();
      this.AccountMb(res.data);
    },

3、导出word文档(点击对应按钮,拿到地址,然后下载)


 Bpm(command) {
      //command.command_txt是"{url}/bpm_api/Task/GetContractFile?dataid={dataid}"
      const a = command.command_txt.replace(/{dataid}/, this.Form.dataid);
      const b = a.replace(/{url}/, "http://192.168.4.213:8011");
      window.open(b, "_blank"); //相当于是打开新页面,然后直接下载
      //window.location.href = b;//这也可以直接下载
    },

或者是另一种方法(此方法如果不成功,需要在request.js文件对返回的状态码进行处理,下面有写)


// 自定义按钮---很多功能
    Bpm(command) {
       const a = command.command_txt.replace(/{dataid}/, this.Form.dataid);
       const b = a.replace(/{url}/, "");
       const c = b.split("?");
       BPMALL(c[0], "get", { dataid: this.Form.dataid }, "blob").then((res) => {
         // 这里是下载文件的方法
         if (!res.code) {
           const blob = new Blob([res], {
             type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
           });
           var fileName = command.name;
           const elink = document.createElement("a");
           elink.download = fileName;
           elink.style.display = "none";
           elink.href = URL.createObjectURL(blob);
           document.body.appendChild(elink);
           elink.click();
           URL.revokeObjectURL(elink.href);
           document.body.removeChild(elink);
         } else {
           // 其他方法
           console.log(res);
         }
       });
    },

src/api/Bpm.js


import requestBpm from "@/utils/request_bpm";

// 自定义按钮,根据后端返回的动态地址进行调用接口
export function BPMALL(url, method, params, responseType) {
  return requestBpm({
    url,
    method,
    responseType,
    params,
  });
}

src/utils/request_bpm.js


import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
// import qs from "qs";
// axios.defaults.headers.get["Content-Type"] = "multipart/form-data";
// axios.defaults.headers.get["Content-Type"] = "application/json";

// create an axios instance
const service2 = axios.create({
  baseURL: process.env.VUE_APP_BASE_API_BPM, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000, // request timeout
});

// request interceptor
service2.interceptors.request.use(
  (config) => {
    // do something before request is sent
    // if (config.method == "get") {
    //   config.data = qs.stringify(config.data);
    // }
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["token"] = getToken();
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service2.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    // 这是给下载文件流的,因为后端返回的没有code,直接是二进制
    if (!res.code) {
      return res;
    }
    if (res.code !== 200) {
      Message({
        message: res.msg || "Error",
        type: "error",
        duration: 5 * 1000,
      });
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm(
          "You have been logged out, you can cancel to stay on this page, or log in again",
          "Confirm logout",
          {
            confirmButtonText: "Re-Login",
            cancelButtonText: "Cancel",
            type: "warning",
          }
        ).then(() => {
          store.dispatch("user/resetToken").then(() => {
            location.reload();
          });
        });
      }
      return Promise.reject(new Error(res.msg || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    console.log("err" + error); // for debug
    Message({
      message: error.msg,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service2;

补充说明type的填写类型


.doc     application/msword
.docx   application/vnd.openxmlformats-officedocument.wordprocessingml.document
.rtf       application/rtf
.xls     application/vnd.ms-excel application/x-excel
.xlsx    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.ppt     application/vnd.ms-powerpoint
.pptx    application/vnd.openxmlformats-officedocument.presentationml.presentation
.pps     application/vnd.ms-powerpoint
.ppsx   application/vnd.openxmlformats-officedocument.presentationml.slideshow
.pdf     application/pdf
.swf    application/x-shockwave-flash
.dll      application/x-msdownload
.exe    application/octet-stream
.msi    application/octet-stream
.chm    application/octet-stream
.cab    application/octet-stream
.ocx    application/octet-stream
.rar     application/octet-stream
.tar     application/x-tar
.tgz    application/x-compressed
.zip    application/x-zip-compressed
.z       application/x-compress
.wav   audio/wav
.wma   audio/x-ms-wma
.wmv   video/x-ms-wmv
.mp3 .mp2 .mpe .mpeg .mpg     audio/mpeg
.rm     application/vnd.rn-realmedia
.mid .midi .rmi     audio/mid
.bmp     image/bmp
.gif     image/gif
.png    image/png
.tif .tiff    image/tiff
.jpe .jpeg .jpg     image/jpeg
.txt      text/plain
.xml     text/xml
.html     text/html
.css      text/css
.js        text/javascript
.mht .mhtml   message/rfc822


".*"="application/octet-stream"  
".001"="application/x-001"  
".301"="application/x-301"  
".323"="text/h323"  
".906"="application/x-906"  
".907"="drawing/907"  
".a11"="application/x-a11"  
".acp"="audio/x-mei-aac"  
".ai"="application/postscript"  
".aif"="audio/aiff"  
".aifc"="audio/aiff"  
".aiff"="audio/aiff"  
".anv"="application/x-anv"  
".asa"="text/asa"  
".asf"="video/x-ms-asf"  
".asp"="text/asp"  
".asx"="video/x-ms-asf"  
".au"="audio/basic"  
".avi"="video/avi"  
".awf"="application/vnd.adobe.workflow"  
".biz"="text/xml"  
".bmp"="application/x-bmp"  
".bot"="application/x-bot"  
".c4t"="application/x-c4t"  
".c90"="application/x-c90"  
".cal"="application/x-cals"  
".cat"="application/vnd.ms-pki.seccat"  
".cdf"="application/x-netcdf"  
".cdr"="application/x-cdr"  
".cel"="application/x-cel"  
".cer"="application/x-x509-ca-cert"  
".cg4"="application/x-g4"  
".cgm"="application/x-cgm"  
".cit"="application/x-cit"  

responseType的类型


""  responseType 设为空字符串与设置为"text"相同,默认类型
"text"  返回的是包含在 DOMString 对象中的文本。
"document"  返回的是一个 HTML Document 或 XML XMLDocument
"arraybuffer"  返回的是一个包含二进制数据的 JavaScript ArrayBuffer 
"blob"  返回的是一个包含二进制数据的 Blob 对象
"json"  返回的是一个 JavaScript 对象 。这个对象是通过将接收到的数据类型视为 JSON 解析得到的。
"ms-stream"  返回的是下载流的一部分 ;此响应类型仅允许下载请求,并且仅受Internet Explorer支持

这篇文章看完如果您觉得有所收获,认为还行的话,就点个赞收藏一下呗

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring4GWT GWT Spring 使得在 Spring 框架下构造 GWT 应用变得很简单,提供一个易于理解的依赖注入和RPC机制。 Java扫雷游戏 JVMine JVMine用Applets开发的扫雷游戏,可在线玩。 public class JVMine extends java.applet.Applet 简单实现!~ 网页表格组件 GWT Advanced Table GWT Advanced Table 是一个基于 GWT 框架的网页表格组件,可实现分页数据显示、数据排序和过滤等功能! Google Tag Library 该标记库和 Google 有关。使用该标记库,利用 Google 为你的网站提供网站查询,并且可以直接在你的网页里面显示搜查的结果。 github-java-api github-java-api 是 Github 网站 API 的 Java 语言版本。 java缓存工具 SimpleCache SimpleCache 是一个简单易用的java缓存工具,用来简化缓存代码的编写,让你摆脱单调乏味的重复工作!1. 完全透明的缓存支持,对业务代码零侵入 2. 支持使用Redis和Memcached作为后端缓存。3. 支持缓存数据分区规则的定义 4. 使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将列表数据缓存到redis中,其他kv结构数据继续缓存到memcached 6. 支持redis的主从集群,可以做读写分离。缓存读取自redis的slave节点,写入到redis的master节点。 Java对象的SQL接口 JoSQL JoSQL(SQLforJavaObjects)为Java开发者提供运用SQL语句来操作Java对象集的能力.利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类需求可以通过快速配置来开发。AutoTips基于搜索引擎Apache Lucene实现。AutoTips提供统一UI。 WAP浏览器 j2wap j2wap 是一个基于Java的WAP浏览器,目前处于BETA测试阶段。它支持WAP 1.2规范,除了WTLS 和WBMP。 Java注册表操作类 jared jared是一个用来操作Windows注册表的 Java 类库,你可以用来对注册表信息进行读写。 GIF动画制作工具 GiftedMotion GiftedMotion是一个很小的,免费而且易于使用图像互换格式动画是能够设计一个有趣的动画了一系列的数字图像。使用简便和直截了当,用户只需要加载的图片和调整帧您想要的,如位置,时间显示和处理方法前帧。 Java的PList类库 Blister Blister是一个用于操作苹果二进制PList文件格式的Java开源类库(可用于发送数据给iOS应用程序)。 重复文件检查工具 FindDup.tar FindDup 是一个简单易用的工具,用来检查计算机上重复的文件。 OpenID的Java客户端 JOpenID JOpenID是一个轻量级的OpenID 2.0 Java客户端,仅50KB+(含源代码),允许任何Web网站通过OpenID支持用户直接登录而无需注册,例如Google Account或Yahoo Account。 JActor的文件持久化组件 JFile JFile 是 JActor 的文件持久化组件,以及一个高吞吐量的可靠事务日志组件。 Google地图JSP标签库 利用Google:maps JSP标签库就能够在你的Web站点上实现GoogleMaps的所有功能而且不需要javascript或AJAX编程。它还能够与JSTL相结合生成数据库驱动的动态Maps。 OAuth 实现框架 Agorava Agorava 是一个实现了 OAuth 1.0a 和 OAuth 2.0 的框架,提供了简单的方式通过社交媒体进行身份认证的功能。 Eclipse的JavaScript插件 JSEditor JSEditor 是 Eclipse 下编辑 JavaScript 源码的插件,提供语法高亮以及一些通用的面向对象方法。 Java数据库连接池 BoneCP BoneCP 是一个高性能的开源java数据库连接池实现库。它的设计初衷就是为了提高数据库连接池的性能,根据某些测试数据发现,BoneCP是最快的连接池。BoneCP很小,只有四十几K

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值