Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 download attribute doesn't work, Forcing file rename on download

I am trying for weeks to change the name of the file being downloaded. But still no luck. Instead of file name to be Chrysanthemum.jpg, it becomes the hash of the file, i.e. 241693260.jpg

In my back-end I am using Node.js and Express.js to handle file upload/download. I am hashing the file name and attributes to make sure files are not getting overwritten.

Here is the HTML code:

<a class="btn btn-info" href="http://localhost:3000/getAttachments?name=Chrysanthemum.jpg&amp;type=image%2Fjpeg&amp;size=879394&amp;lastModified=1247549551674&amp;extension=jpg" download="Chrysanthemum.jpg" target="_blank">Download File</a>

Here is my back-end:

app.use('/uploads', express.static(__dirname + "/uploads"));

app.get("/getAttachments", function (req, res) {
    try {
        var fileToBeSent = hashCode(req.query.name + req.query.type + req.query.size + req.query.lastModified + req.query.extension);
        fileToBeSent += req.query.extension  ? '.' + req.query.extension : '';

    // res.sendFile("./uploads/" + fileToBeSent, {
    //     root: __dirname,
    //     "Content-Disposition": '"attachment; filename="' + (req.query.extension  ? '.' + req.query.extension : '') + '"',
    //     "Content-Type": "application/octet-stream"
    // });

        res.redirect("/uploads/" + fileToBeSent);
    } catch (err) {
        console.log("an attempt to GET a file that doesn't exist.");
    }
});

So as I am renaming the file name in my back-end, I am trying to rename file back to it's original name using HTML5 but I am not being successful.

UPDATE: Using the express's sendFile result in the same issue.

UPDATE: My server is uses cross-origin

like image 440
Node.JS Avatar asked Oct 29 '25 16:10

Node.JS


2 Answers

I met this problem a year ago and spent a lot of time before found that this is potential problem of Chrome Prove for version 35 and later Avoiding repeating names you can use static id with increment. Hope this answer will be helpful

like image 132
xtraicecat Avatar answered Oct 31 '25 06:10

xtraicecat


All you should have to do is to provide the entire file name that you want the file to be downloaded as. In your Content-Disposition it doesn't look like you were providing the entire filename.

res.sendFile(__dirname + "/uploads/" + fileToBeSent, {
        headers: {
            'Content-Disposition': 'attachment; filename="' + req.query.name + '"'
        }
    });
like image 35
Brian Shotola Avatar answered Oct 31 '25 05:10

Brian Shotola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!