Download picture front-end summary

Download picture front-end summary

Front-end download pictures divided into two categories: one server with the realization (that is, download resources back-office services provided); the second is a pure front-end download

1, the server with the realization

For this case, the front end of the development is very simple, requires only a a label, such as:

<a href='/api/download' >下载图片</a>

When a file is accessed directly, if the file is a binary and other browsers can not resolve the file, the browser will download the file, but if the browser can parse the file yourself, it will open the file and to their own presented in a way out, but not download, then you need to set the message response header that tells the browser needs to download the file rather than a simple open.
This time backstage to get a service request and response headers setting message, to tell the browser needs to download the file. To node, for example:

app.get('/api/download/', (req, res, next) => {//以文件流的形式下载文件
    var filePath = path.join(__dirname, '../src/images/erwei.jpg');
    var stats = fs.statSync(filePath);
    res.set({
        'Content-Type': 'application/octet-stream', //告诉浏览器这是一个二进制文件
        'Content-Disposition': 'attachment; filename=111', //告诉浏览器这是一个需要下载的文件
        'Content-Length': stats.size  //文件大小
    });
    fs.createReadStream(filePath).pipe(res);
});

2, pure front-end download

Which is divided into two situations: First, download the source picture (as picture files in the folder of the project); the second is a static resource cross-domain websites (such as your company's CDN static resources)

a. Download the source picture

This situation is the use of a simple label downlaod can be achieved, for example:

<a href=‘../img/test.png’ download="img" >下载图片</a>

b. to download a URL site's images

With canvas, cases

// 调用方式
// 参数一: src
// 参数二: 图片名称,可选
export const downloadImage = (src: string, name: string) => {
    const image = new Image();
    // 解决跨域 canvas 污染问题
    image.setAttribute('crossOrigin','anonymous');
    image.onload = function(){
      const canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      const context = canvas.getContext('2d');
      context.drawImage(image,0,0,image.width,image.height);
      const url = canvas.toDataURL('image/png');
      // 生成一个 a 标签
      const a = document.createElement('a');
      // 创建一个点击事件
      const event = new MouseEvent('click');
      // 将 a 的 download 属性设置为我们想要下载的图片的名称,若 name 不存在则使用'图片'作为默认名称
      a.download = name || '图片';
      // 将生成的 URL 设置为 a.href 属性
      a.href = url;
      // 触发 a 的点击事件
      a.dispatchEvent(event);
    };
    image.src = src
}

Guess you like

Origin www.cnblogs.com/jlfw/p/11817980.html