react下载图片实现
使用 fetch 和 Blob 下载图片
在 React 中通过 fetch API 获取图片数据,转换为 Blob 对象后创建下载链接。这种方法适用于需要处理跨域或动态生成图片的场景。
const downloadImage = async (url, filename) => {
try {
const response = await fetch(url);
const blob = await response.blob();
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.download = filename || 'image.jpg';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(downloadUrl);
} catch (error) {
console.error('Download failed:', error);
}
};
使用 HTMLAnchorElement 直接下载
对于公开可访问的静态图片资源,直接创建 <a> 标签触发下载是最简单的方式。注意某些浏览器可能会直接打开图片而非下载。
const downloadImage = (url, filename) => {
const link = document.createElement('a');
link.href = url;
link.download = filename || url.split('/').pop();
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
使用 FileSaver.js 库
第三方库 FileSaver.js 提供了更简洁的 API,支持大文件下载和 Blob 处理。先安装依赖:
npm install file-saver
实现代码示例:
import { saveAs } from 'file-saver';
const downloadImage = (url, filename) => {
fetch(url)
.then(res => res.blob())
.then(blob => saveAs(blob, filename || 'image.png'))
.catch(console.error);
};
处理 Canvas 生成的图片
当需要下载通过 Canvas 绘制的动态内容时,使用 toDataURL 转换后下载:
const downloadCanvasImage = (canvasId, filename) => {
const canvas = document.getElementById(canvasId);
const dataURL = canvas.toDataURL('image/png');
const link = document.createElement('a');
link.download = filename || 'canvas-image.png';
link.href = dataURL;
link.click();
};
注意事项
- 跨域问题:若图片服务器未配置 CORS 策略,
fetch方式可能失败,需确保服务器允许跨域或使用代理。 - 文件名处理:建议始终指定文件名及扩展名(如
.jpg,.png),避免浏览器默认行为不一致。 - 用户交互:部分浏览器要求下载操作必须由用户手势(如点击事件)直接触发,不能在异步回调中直接调用。







