Commonly used front-end file download and upload methods

JenK
中文

This article sorts out the commonly used download files and methods of uploading files on the front end
The examples are all based on vue + element ui + axios . The el not used, and the encapsulation is implemented here.

First attach demo

upload files

Take pictures as an example, file upload can omit the preview picture function

There are two ways to upload pictures: file stream and base64 ;

1. File stream upload + preview:

  <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
      });
}

Browser network view
image.png
image.png
img element view src , type blob
image.png

2. Base64 upload + preview:

<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]);
      }
    }

Browser network view
image.png

img element view src , type base64
image.png

download file

Picture download

Suppose the image to be downloaded is url , and the file stream the same as this

  <el-image style="width: 100px; height: 100px" :src="downloadImgSrc"></el-image>
  <el-button type="warning" round plain size="mini" @click='downloadImg'>点击下载</el-button>
  • Note: Here you need to specify responseType as blob
//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);
      });
    }

File download (take pdf as an example)

  <el-image style="width: 100px; height: 100px" :src="downloadImgSrc"></el-image>
  <el-button type="warning" round plain size="mini" @click='downloadImg'>点击下载</el-button>
  • Note: Here you need to specify responseType as blob
//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);
      });
    }

For pdf preview, please refer to how to preview and download the pdf file

summary

demo review

Image upload can use 2 ways: file stream and Base64
The same is true for picture downloading.

WX20210922-091703.png

阅读 1.8k
avatar
JenK
北京中电兴发 前端工程师

理想的光芒很难照进现实

7.6k 声望
5.9k 粉丝
0 条评论
你知道吗?

avatar
JenK
北京中电兴发 前端工程师

理想的光芒很难照进现实

7.6k 声望
5.9k 粉丝
宣传栏