js圖片下載方式集合(附詳細代碼)
更新時間:2024年01月18日 09:24:53 作者:失眠時間
關于圖片下載問題,不同的瀏覽器,需要兼容的下載方式,這篇文章主要給大家介紹了關于js圖片下載方式的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
一、文件流格式下載
創(chuàng)建 a 標簽下載文件流格式圖片
/**
* 創(chuàng)建 <a> 標簽下載文件流格式圖片
* @param file
* @param fileName
*/
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')
};
}
二、鏈接格式下載
/**
* 根據(jù)圖片路徑下載
* @param imgsrc 圖片路徑
* @param name 下載圖片名稱
* @param type 格式圖片,可選,默認png ,可選 png/jpeg
*/
export const downloadImage = (imgsrc: string, name: string, type: string = 'png') => {
let image = new Image();
// 解決跨域 Canvas 污染問題
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}`); //得到圖片的base64編碼數(shù)據(jù)
let a = document.createElement("a"); // 生成一個a元素
let event = new MouseEvent("click"); // 創(chuàng)建一個單擊事件
a.download = name || "pic"; // 設置圖片名稱
a.href = url; // 將生成的URL設置為a.href屬性
a.dispatchEvent(event); // 觸發(fā)a的單擊事件
}
//將資源鏈接賦值過去,才能觸發(fā)image.onload 事件
image.src = imgsrc
}總結
到此這篇關于js圖片下載方式的文章就介紹到這了,更多相關js圖片下載方式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解JavaScript數(shù)組reduce()方法的高級技巧
reduce()?是?JavaScript?中一個很有用的數(shù)組方法,這篇文章主要介紹了JavaScript中reduce()方法的高級技巧,感興趣的小伙伴可以了解一下2023-03-03

