How to download a base64-encoded image?

前端 未结 10 917
无人及你
无人及你 2020-11-29 08:16

I have a base64-encoded image from the server for which I want to force the download through JavaScript. Is is possible?

10条回答
  •  情歌与酒
    2020-11-29 08:52

    It is so simple just use function below:

    // Parameters:
    // contentType: The content type of your file. 
    //              its like application/pdf or application/msword or image/jpeg or
    //              image/png and so on
    // base64Data: Its your actual base64 data
    // fileName: Its the file name of the file which will be downloaded. 
    
    function downloadBase64File(contentType, base64Data, fileName) {
         const linkSource = `data:${contentType};base64,${base64Data}`;
         const downloadLink = document.createElement("a");
         downloadLink.href = linkSource;
         downloadLink.download = fileName;
         downloadLink.click();
    }
    

提交回复
热议问题