Seems like many people have ran into similar kind of problem but googling hasn't helped me so far. I'm trying to serve the file to the user and automatically prompt download on client side, but all I'm getting is "The image cannot be displayed because it contains errors.
Here is my client side code:
function downloadFile(passcode){
console.log(passcode);
const payload = {"password" : passcode.toLowerCase()}
axios.post(downloadUrl, payload, {
headers : {'Content-Type' : 'application/json'}
})
.then((res) => {
console.log(res.data)
window.open(downloadUrl + '/' + res.data)
})
}
So the user types in a passcode, and clicks on the download button and should get the appropriate file. New tab opens but file doesn't stard downloading. Here is my server side:
const getFilePath = async (req, res) => {
const passcode = req.body.password
try {
fs.readdir(path.join(homeDir + '/uploads/' + passcode), 'utf-8',(err, files) => {
files.forEach((file) => {
const filename = passcode + '/' + file
try {
res.send(filename)
res.end()
} catch (error) {
console.log(error);
}
})
})
} catch (error) {
console.log(error);
}
}
const fileDownload = async (req, res) => {
const {dir: directory, file: fileName} = req.params
const filePath = path.join(homeDir + '/uploads/' + directory + '/' + fileName)
fs.access(filePath, fs.constants.F_OK, err => {
//check that we can access the file
console.log(`${filePath} ${err ? "does not exist" : "exists"}`);
});
res.download(filePath)
res.end()
}
I even check the file with fs.access and it returns true (it prints {filepath} exists), but the file is not served at all.
Any kind of help is much appreciated!
EDIT: Decided to work on my front end a bit to cool off, came back and immidiatelly noticed res.end() just below send file, which ends the transmission. Removed it and it works like a charm!