Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
React unable to download PDF from anchor tag

I'm trying to download a document with react. I have this in my code right now:

<li><a href={this.state.invoice.pathToFile}>Download Invoice</a></li>

The path to the file looks like this:

C:\bin\documents\invoices\invoice-01-01-2021.pdf

Everytime we click the link to download the file, We are sent back to the homepage. I would expect it to just download the file. When I hover over the download link it does display the file location: Image of the file location

Not sure what's going on or causing this.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

This is not a react issue. Add the download attribute to the anchor <a> so that the browser will download the file

<li><a href={this.state.invoice.pathToFile} download>Download Invoice</a></li>

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use download attribute to the anchor element to save files, if you reference the file correctly, like this:

<a href="Your file location" download>Download</a>

And in your case it should be like this:

<li><a href={this.state.invoice.pathToFile} download>Download Invoice</a></li>
about 4 years ago · Juan Pablo Isaza Denunciar

0

Neither of these solutions ended up working. On the back-end I had to implement a downloads controller like so:

[HttpPost]
    public ActionResult GetInvoiceDocument([FromBody] string PathToFile)
    {
        byte[] fileBytes = System.IO.File.ReadAllBytes(PathToFile);
        var fileName = PathToFile.Split("/")[3];
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
    }

On the front-end I created an method that gets called onClick. This downloads a document and then appends an anchor tag to the DOM and instantly downloads the file.

downloadFile = (e : any, filePath : string) => {
    e.preventDefault();
    let options = {
        method : "POST",
        headers : {
            'Accept' : 'application/json',
            'Content-Type' : 'application/json;charset=UTF-8'
        },
        body : JSON.stringify(filePath)
    };

    fetch('https://localhost:44304/api/DownloadDocument', options).then(async res => ({
        filename: this.state.invoice.pathToFile!.split('/')[3]!,
        blob : await res.blob()
    })). then(resObj => {
        const newBlob = new Blob([resObj.blob], { type : 'application/pdf'});
        const objUrl = window.URL.createObjectURL(newBlob);

        let link = document.createElement('a');
        link.href = objUrl;
        link.download = resObj.filename;
        link.click();

        setTimeout(() => { window.URL.revokeObjectURL(objUrl); }, 250);
    })
    
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda