I am looking to display a list of available documents to the user that they can choose to either view in browser or download to their device. The downloading part is already done and working, however I can't seem to put together the correct way to have Node and React open the document in the user's browser for viewing.
Currently I have this in my React frontend:
const fetchFile = async (operation, path, fileName) => {
Axios.get(
`http://localhost:8080/api${path}`,
{ responseType: 'blob' })
.then(res => {
return res.data
})
.then(blob => {
let url
const link = document.createElement('a')
if (operation === "1") {
url = URL.createObjectURL(blob)
window.open(url)
}
else {
url = window.URL.createObjectURL(blob)
link.href = url
link.download = fileName
}
document.body.appendChild(link)
link.click()
link.remove()
URL.revokeObjectURL(url)
})
.catch(err => console.log(err))
}
This is the function handling the API call and in case of the operation
variable being 1 it should open it in browser, while otherwise it's a download.
While in the Node.js backend currently I'm trying the res.sendFile()
function:
function openDocument(res, path) {
res.sendFile(path, {root: __dirname});
}
However right now this runs into an ENOENT error. It seems it tries to open the file in a format of index.html and extends the filename with it, however obviously it won't find it like that in the path.
So how am I really supposed to have my webapp open a document sent from the backend in the browser for viewing? Is that actually possible?
sendFile
should just send the file with the right mime type, how the browser handles them is up to the browser.