文章目录
一、文件流格式下载
创建 a
标签下载文件流格式图片
| |
| |
| |
| |
| |
| export const downloadFile = (file: string, fileName?: string) => { |
| const blob = new Blob([file]); |
| const fileReader = new FileReader(); |
| fileReader.readAsDataURL(blob); |
| fileReader.onload = (e) => { |
| const a = document.createElement("a"); |
| a.download = fileName || '0123456.PNG'; |
| a.href = e.target?.result as string; |
| document.body.appendChild(a); |
| a.click(); |
| document.body.removeChild(a); |
| }; |
| } |
复制
文件流格式还可以转为Base64格式之后,再以链接格式下载
转换方式如下
| export const downloadFileUrl = (file: Blob) => { |
| const blob = new Blob([file]); |
| const fileReader = new FileReader(); |
| fileReader.readAsDataURL(blob); |
| fileReader.onload = (e) => { |
| const url = e.target?.result as string; |
| downloadImage(`data:image/png;Base64,${url}`, 'testefd') |
| }; |
| } |
复制
二、链接格式下载
| |
| |
| |
| |
| |
| |
| export const downloadImage = (imgsrc: string, name: string, type: string = 'png') => { |
| let image = new Image(); |
| |
| image.setAttribute("crossOrigin", "anonymous"); |
| image.onload = function () { |
| let canvas = document.createElement("canvas"); |
| canvas.width = image.width; |
| canvas.height = image.height; |
| let context = canvas.getContext("2d"); |
| context?.drawImage(image, 0, 0, image.width, image.height); |
| let url = canvas.toDataURL(`image/${type}`); |
| let a = document.createElement("a"); |
| let event = new MouseEvent("click"); |
| a.download = name || "pic"; |
| a.href = url; |
| a.dispatchEvent(event); |
| } |
| |
| image.src = imgsrc |
| } |
复制