2

I am using this function to download the image I am getting from server on frontend of my app.

    const downloadImage = () => {
        fetch(`url`, {
            method: 'GET',
            headers: {
                'Content-Type': 'image/png',
                'Content-Disposition': 'attachment',
            },
        })
        .then((response) => response.blob())
        .then((blob) => {
            // Create blob link to download
            const url = window.URL.createObjectURL(
                new Blob([blob]),
            );
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute(
                'download',
                `FileName.png`,
            );
            document.body.appendChild(link);
            link.click();
            link.parentNode.removeChild(link);
        });
    }

its successfully downloading the image but when opening its showing image type not supported

here is image

1 Answers1

3

I think this one will be able to solve your issue. I have used react. This answer is derived from an answer here.

A Working example at codesanbox here.

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const download = (e) => {
    fetch(
      "https://upload.wikimedia.org/wikipedia/en/6/6b/Hello_Web_Series_%28Wordmark%29_Logo.png",
      {
        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.download = "image.png";
          link.click();
        });
      })
      .catch((err) => {
        console.log(err);
      });
  };
  return (
    <div className="App">
      <h1>Hello, you seem to want to know how to download images</h1>
      <a href="javascript:void(0)" onClick={(e) => download(e)}>
        <i className="fa fa-download" />
        download
      </a>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Mehul Thakkar
  • 2,177
  • 13
  • 22