我有我的反应项目,我可以在其中编辑图像并生成新图像。现在我想下载生成的图像。我正在使用 cloudinary,并且我有图像的 url。
但主要问题是我无法下载图像。我试过了
<a href="link" download> Download </a>
但是没有成功。它只是打开图像但不下载它。
我只想下载图像,仅此而已。
如果您有任何想法请分享
实时沙箱https://codesandbox.io/s/interesting-mountain-lf4lk?file=/src/App.js
您不需要外部库来实现该功能。只需添加 Cloudinary
flags
=> attachment
转换(URL 中的 fl_attachment
),即可将 Content-Disposition
标头设置为“attachment”,然后文件就会下载。
<a href="https://res.cloudinary.com/demo/image/upload/fl_attachment/sample.jpg">Download</a>
您可以选择使用格式
fl_attachment:my_custom_filename
设置下载文件的自定义文件名。
<a href="https://res.cloudinary.com/demo/image/upload/fl_attachment:my_custom_filename/sample.jpg">Download</a>
我使用了js-file-download。工作样本: https://codesandbox.io/s/confident-monad-pc6l9?file=/src/App.js:76-92
import fileDownload from "js-file-download";
fileDownload(url, filename);
使用cloudinary转换URL添加附件,这会生成一个新的URL来直接下载您的文件。
例如:
//id is your public_id file in cloudinary
export const getImageAttachment = async (id) => {
return await cloudinary.url(id, {
flags: "attachment:imgname"
})
这会返回一个新的 URL,您可以使用添加
<a/>
标签 href={}
例如,然后下载您的文件。
希望我有所帮助。
更多信息: https://cloudinary.com/documentation/transformation_reference#fl_attachment