前端下载图片(文件)以及打包下载图片(文件)

平时前端点开图片都是在线查看的,如果我们想下载图片怎么办呢?

下面的下载都是以图片为例,其他文件 如视频文件也是适用于下列方法的.


1、单张图片下载:

1.1 原生js网络请求方式

<button (click)="downSingleImg()">下载单张图片</button>
downSingleImg() {
    
    
  const url = 'https://tse1-mm.cn.bing.net/th/id/OET.625d80efe5644911a2c926ad8f08a365?w=272&h=135&c=7&rs=1&o=5&pid=1.9';

  this.getFileBlob(url).then((res) => {
    
    
    const a = document.createElement('a');
    const href = window.URL.createObjectURL(res);
    a.href = href;
    a.download = 'photo.png'; // 设置图片名称 ,格式自己定
    a.click();
    a.remove();
    window.URL.revokeObjectURL(href);
  });
}

getFileBlob(url: any) {
    
    
  return new Promise((resolve) => {
    
    
    const xhr = new XMLHttpRequest();

    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = () => {
    
    
      if (xhr.status === 200) {
    
    
        resolve(xhr.response);
      }
    };
    xhr.send();
  });
}

1.2 angular http请求方式

// ts中
downSingleImg() {
    
    
  this.uploadFileService.getFile(url).subscribe((res) => {
    
    
    const a = document.createElement('a');
    const href = window.URL.createObjectURL(res);
    a.href = href;
    a.download = 'photo'; // 设置图片名称
    a.click();
    a.remove();
    window.URL.revokeObjectURL(href);
  });
}

// 服务里:
getFile(url: string) {
    
    
  return this.http.get(url, {
    
    
    responseType: 'blob'
  });
}

1.3 axios请求方式

// 安装
$ npm install axios

// 引用
import axios from 'axios';

// 下载
downSingleImg() {
    
    
    const url = 'https://tse1-mm.cn.bing.net/th/id/OET.625d80efe5644911a2c926ad8f08a365?w=272&h=135&c=7&rs=1&o=5&pid=1.9';
  
    axios.get(url, {
    
     responseType: 'blob' }).then((res: any) => {
    
    
      const a = document.createElement('a');
      const href = window.URL.createObjectURL(res.data); // 注意这里是res.data,不是res
      a.href = href;
      a.download = 'photo'; 
      a.click();
      a.remove();
      window.URL.revokeObjectURL(href);
    });
}

注意:上面三种请求方式选其一即可。

2、打包下载

可以根据项目需求设置打包下载的文件列表格式

例子:

<button (click)="downPackageImg()">打包下载图片</button>
// 安装
npm install file-saver
npm install jszip

// 引用
import JSZip from 'jszip';
import FileSaver from 'file-saver';

// 打包下载
downPackageImg() {
    
    
  const data = [
    {
    
    
      // 这个名字后缀是要有图片格式的
      fileName: '蒙版1.svg',
      url: 'http://design-svc.fat.lunz.cn/StaticFiles/BP9999999772/BV9999999422/SA9999998420/4dc8463e-8ac6-4eb4-862c-783bf486a242.svg'
    },
    {
    
    
      fileName: '蒙版2.svg',
      url: 'http://design-svc.fat.lunz.cn/StaticFiles/BP9999999772/BV9999999422/SA9999998420/30df266a-485e-411e-b178-b9fb1d8e0748.svg'
    }
  ];

  const zip = new JSZip();
  const cache = {
    
    };
  const promises: any = [];

  data.forEach((item: any) => {
    
    
    const promise = this.getFile(item.url).then((res: Blob) => {
    
    
      zip.file(item.fileName, res, {
    
    
        binary: true
      });
      cache[item.fileName] = res;
    });
    promises.push(promise);
  });

  Promise.all(promises).then(() => {
    
    
    zip
      .generateAsync({
    
    
      type: 'blob'
    })
      .then((content) => {
    
    
      // 生成二进制流
      FileSaver.saveAs(content, 'file.zip'); // 利用file-saver保存文件
    });
  });
}

// http网络请求方式
getFile(url: string) {
    
    
  return new Promise((resolve, reject) => {
    
    
    // http请求
    this.uploadFileService
      .getFileSource(url)
      .toPromise()
      .then((data) => {
    
    
      resolve(data);
    })
      .catch((error) => {
    
    
      reject(error.toString());
    });
  });
}

// 在uploadFileService服务里写:
getFileSource(url: string) {
    
    
  return this.http.get(url, {
    
    
    responseType: 'blob'
  });
}

上面的http请求也可以改为axios请求,如果用axios请求的话就不用在服务里写了。

// 安装
npm install axios

// 引用
import axios from 'axios';

// axios请求
getFile(url: string) {
    
    
  return new Promise((resolve, reject) => {
    
    
    axios({
    
    
      method: 'get',
      url,
      responseType: 'arraybuffer'
    })
      .then((data) => {
    
    
      resolve(data.data);
    })
      .catch((error) => {
    
    
      reject(error.toString());
    });
  });
}

注意: 上面的http请求和axios请求方式,两者其一就行

猜你喜欢

转载自blog.csdn.net/qq_42667613/article/details/121798716