当前位置:主页 > 查看内容

前端常用图片文件下载上传方法

发布时间:2021-04-25 00:00| 位朋友查看

简介:本文整理了前端常用的下载文件以及上传文件的方法 例子均以 vue + element ui + axios 为例,不使用 el 封装好的上传组件,这里自行进行封装实现 先附上 demo 上传文件 以图片为例,文件上传可以省略预览图片功能 图片上传可以使用2种方式: 文件流 和 base64……

本文整理了前端常用的下载文件以及上传文件的方法
例子均以vue+element ui+axios为例,不使用el封装好的上传组件,这里自行进行封装实现

先附上demo

上传文件

以图片为例,文件上传可以省略预览图片功能

图片上传可以使用2种方式:文件流base64;

1.文件流上传+预览

  <input type="file" id='imgBlob' @change='changeImgBlob' />
  <el-image style="width: 100px; height: 100px" :src="imgBlobSrc"></el-image>
// data
imgBlobSrc: ""

// methods
changeImgBlob() {
      let file = document.querySelector("#imgBlob");
      /**
       *图片预览
       *更适合PC端,兼容ie7+,主要功能点是window.URL.createObjectURL
       */
      var ua = navigator.userAgent.toLowerCase();
      if (/msie/.test(ua)) {
        this.imgBlobSrc = file.value;
      } else {
        this.imgBlobSrc = window.URL.createObjectURL(file.files[0]);
      }
      //上传后台
      const fd = new FormData();
      fd.append("files", file.files[0]);
      fd.append("xxxx", 11111); //其他字段,根据实际情况来
      axios({
        url: "/yoorUrl", //URL,根据实际情况来
        method: "post",
        headers: { "Content-Type": "multipart/form-data" },
        data: fd
      });
}

浏览器network查看
image.png
image.png
img元素查看src,为blob类型
image.png

2.Base64上传+预览

<input type="file" id='imgBase' @change='changeImgBase' />
<el-image style="width: 100px; height: 100px" :src="imgBaseSrc"></el-image>
// data
imgBaseSrc : ""

// methods
    changeImgBase() {
      let that = this;
      let file = document.querySelector("#imgBase");
      /**
      *图片预览
      *更适合H5页面,兼容ie10+,图片base64显示,主要功能点是FileReader和readAsDataURL
      */
      if (window.FileReader) {
        var fr = new FileReader();
        fr.onloadend = function (e) {
          that.imgBaseSrc = e.target.result;
          //上传后台
          axios({
            url: "/yoorUrl", //URL,根据实际情况来
            method: "post",
            data: {
              files: that.imgBaseSrc
            }
          });
        };
        fr.readAsDataURL(file.files[0]);
      }
    }

浏览器network查看
image.png

img元素查看src,为base64类型
image.png

下载文件

图片下载

假设需要下载图片为url文件流处理和这个一样

  <el-image style="width: 100px; height: 100px" :src="downloadImgSrc"></el-image>
  <el-button type="warning" round plain size="mini" @click='downloadImg'>点击下载</el-button>
  • 注意:这里需要指定 responseTypeblob
//data
 downloadImgSrc:'https://i.picsum.photos/id/452/400/300.jpg?hmac=0-o_NOka_K6sQ_sUD84nxkExoDk3Bc0Qi7Y541CQZEs'
//methods
downloadImg() {
      axios({
        url: this.downloadImgSrc, //URL,根据实际情况来
        method: "get",
        responseType: "blob"
      }).then(function (response) {
        const link = document.createElement("a");
        let blob = new Blob([response.data], { type: response.data.type });
        let url = URL.createObjectURL(blob);
        link.href = url;
        link.download = `实际需要的文件名.${response.data.type.split('/')[1]}`;
        link.click();
        document.body.removeChild(link);
      });
    }

文件下载(以pdf为例)

  <el-image style="width: 100px; height: 100px" :src="downloadImgSrc"></el-image>
  <el-button type="warning" round plain size="mini" @click='downloadImg'>点击下载</el-button>
  • 注意:这里需要指定 responseTypeblob
//data
 downloadImgSrc:'https://i.picsum.photos/id/452/400/300.jpg?hmac=0-o_NOka_K6sQ_sUD84nxkExoDk3Bc0Qi7Y541CQZEs'
//methods
downloadImg() {
      axios({
        url: this.downloadImgSrc, //URL,根据实际情况来
        method: "get",
        responseType: "blob"
      }).then(function (response) {
        const link = document.createElement("a");
        let blob = new Blob([response.data], { type: response.data.type });
        let url = URL.createObjectURL(blob);
        link.href = url;
        link.download = `实际需要的文件名.${response.data.type.split('/')[1]}`;
        link.click();
        document.body.removeChild(link);
      });
    }

pdf预览可以参考如何预览以及下载pdf文件

小结

图片上传可以使用2种方式文件流Base64
图片下载同理。
更多问题欢迎加入前端交流群交流749539640


本文转自网络,版权归原作者所有,原文链接:https://segmentfault.com/a/1190000039893814
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐