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:

Not sure what's going on or causing this.
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>
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>
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);
})
}