Tengo una aplicación en la que un usuario hace clic en un enlace y se le muestra una copia de una imagen de mi servidor. Mi servidor me está devolviendo el blob. Quiero darle a mi usuario la posibilidad de hacer clic en un botón en esta página y descargar el archivo desde el enlace. Este enlace puede contener un archivo jpeg o incluso un archivo csv. Intenté usar js-file-downloader pero no tuve suerte
Aquí está mi componente de reacción a continuación
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 PreviewMediasúper simple no hay necesidad de una biblioteca externa para esto. ESTO SOLO FUNCIONA PARA URLS DEL MISMO ORIGEN PERO SIRVE PARA MI CASO
<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>