'MERN file download from blob in react
I have an app where a user clicks a link and is shown a copy of an image from my server. My server is returning me the blob. I want to give my user the ability to click a button on this page and download the file from the link. This link may contain a jpeg or even a csv file. I tried using js-file-downloader but no luck
Here is my react component below
import React, {useState, useEffect} from 'react'
import axios from 'axios'
import { Col, Button } from 'reactstrap'
import { fileDownload } from 'js-file-download';
const PreviewMedia = ({match}) => {
const [file, setFile] = useState()
const [image, setImage] = useState()
console.log('image', image)
const handleClick = () => {
window.open(image) <--- this handleClick should be downloading the image state which is a blob
}
useEffect(() => {
try {
axios({
url:`http://localhost:5000/media/${match.params.imageID}`, // <----------first get request
method:"GET"
}).then(res => setFile(res.data))
} catch (error) {
console.log(error)
} }, [])
useEffect(() => {
console.log("this ran")
if(!file) {
} else {
axios({
url: file?.links?.content_direct_temporary, //<----------------returns the blob second get request once done
method:"GET"
}).then(res => {
setImage(res.data) // <--- res.data is a blob
})}
}, [file])
console.log("PREVIEW MEDIA-----------file", file)
return (
<div>
<Col className="text-center">
{image && <img src={image} ></img>} //<--successfully renders image or nothing if file which is fine
</Col>
<Col className="d-flex justify-content-center" >
<Button color="primary" onClick={handleClick} className=" my-3 text-white">
Download file
</Button>
</Col>
</div>
)
}
export default PreviewMedia
Solution 1:[1]
super simple. no need for external library for this. THIS ONLY WORKS FOR SAME ORIGIN URLS THOUGH BUT SERVES MY CASE
<div>
<Col className="text-center">
{image && <img src={image} ></img>} //<--successfully renders image or nothing if file which is fine
</Col>
<Col className="d-flex justify-content-center" >
<a href={image} download > // wrap this anchor tag around button w/ download attribute
<Button color="primary" onClick={handleClick} className=" my-3 text-white">
Download file
</Button>
</a>
</Col>
</div>
<a download="custom-filename.jpg" href="/path/to/image" title="ImageName">
</a>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ErikaPeterson007 |
