Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

113
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda