【发布时间】:2021-07-02 19:42:32
【问题描述】:
我需要一个将图像下载到本地的按钮。但是这些图片来自 Unsplash API。
我找到了一个 HTML download attribute, LIVE DEMO
<p>Click on the image to download it:<p>
<a href="/images/myw3schoolsimage.jpg" download>
<img src="/images/myw3schoolsimage.jpg" alt="W3Schools" width="104" height="142">
</a>
但是如果我想在 React 中使用这个方法是行不通的。原因是我想从 Unsplash API 下载的图像因此无法正常工作!但是,如果我尝试下载属于我的项目目录的本地图像,它就成功了!
import style from "./style.module.css";
import cn from "classnames";
import { BiDownArrowAlt, BiPlus } from "react-icons/bi";
import logo from "../../assets/images/Logo.png";
const ImageCard = ({ image }) => {
return (
<div className={style.image}>
{/* { Download Button } */}
<a href={logo} download target="_blank">
<span className={cn(style.button, style.downloadButton)}>
<BiDownArrowAlt className={style.downloadIcon} />
</span>
</a>
</div>
);
};
这可行,但我的照片来自 API。
我在 StackOverflow 中搜索了这个主题,我找到了 this question。但是这种方法是行不通的。这会下载图像,但图像无法正常工作。
import style from "./style.module.css";
import cn from "classnames";
import { BiDownArrowAlt, BiPlus } from "react-icons/bi";
const download = (e) => {
console.log(e.target.href);
fetch(e.target.href, {
method: "GET",
headers: {},
})
.then((response) => {
response.arrayBuffer().then(function (buffer) {
const url = window.URL.createObjectURL(new Blob([buffer]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "image.png"); //or any other extension
document.body.appendChild(link);
link.click();
});
})
.catch((err) => {
console.log(err);
});
};
const ImageCard = ({ image }) => {
return (
<div className={style.image}>
{/* { Download Button } */}
<a
href={image.links.download}
download
onClick={(e) => download(e)}
target="_blank"
>
<span className={cn(style.button, style.downloadButton)}>
<BiDownArrowAlt className={style.downloadIcon} />
</span>
</a>
);
};
export default ImageCard;
请帮助我解决这个问题!
【问题讨论】:
标签: javascript html reactjs downloadfile