将图像下载为打字稿中的文件 [英] Download image as file in typescript

查看:53
本文介绍了将图像下载为打字稿中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数据库中获取了base64格式的图像,我希望允许用户下载图像.最好的方法是什么?

I get an image in base64 format from the database and I would like to allow the user to download the image. What is the best way to do it?

推荐答案

考虑到您将此问题标记为Angular问题,我想由于某种原因,您不想公开以原始格式提供图像的终结点,然后创建指向它的链接.

Considering you tagged this question as an Angular question, I suppose that for some reason, you dont want to expose an endpoint that serves the image in raw format, then create a link to it.

如果您正在寻找针对Angular的解决方案,那就没有了.但是,下面有一个纯JavaScript解决方案.它可用于预加载图像,以便您的用户可以在需要时立即获取图像.

If you're looking for an Angular specific solution, there is none. However, there is a pure javascript solution described below. It can be used to preload your image so your user will be able to get the image instantly when needed.

let byteCharacters = atob('your base64 data');

let byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}

let byteArray = new Uint8Array(byteNumbers);

let blob = new Blob([byteArray], {"type": "image/jpeg"});

if(navigator.msSaveBlob){
    let filename = 'picture';
    navigator.msSaveBlob(blob, filename);
} else {
    let link = document.createElement("a");

    link.href = URL.createObjectURL(blob);

    link.setAttribute('visibility','hidden');
    link.download = 'picture';

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

您可以在此处进行测试: https://jsfiddle.net/pxm0eyzs/2/

You can test here : https://jsfiddle.net/pxm0eyzs/2/

这篇关于将图像下载为打字稿中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆