HarryJ2213
HarryJ2213

Reputation: 143

How to download a file via URL then get its name

This is for a userscript I'm making with JS+jQuery. I'm wondering if it's possible to find the filename given the URL.

It's in the form of:

http://example.org/download.php?action=download&id=1234

and then that link downloads a file such as "cat.jpg".

How do I find out what the file name is called? I don't need to actually save the file on the users computer - just need to find the name of the file.

I'm open to using any JS library - but I need to make sure that the file isn't actually saved in the users computer (or maybe it's just saved in a temp folder somewhere).

Upvotes: 14

Views: 17011

Answers (1)

dfsq
dfsq

Reputation: 193261

The simple thing you can do is to make HEAD request, so that you don't actually download the file but only response headers. From there you get Content-Disposition header which contains filename field.

Something like this in jQuery:

$.ajax({
    type: "HEAD",
    url: 'http://example.org/download.php?action=download&id=1234',
    success: function(message, text, response) {
        var header = response.getResponseHeader('Content-Disposition');
        console.log(header);
    }
});

header variable will be something like attachment; filename="image.jpg". Now it's easy to extract filename part:

var filename = header.match(/filename="(.+)"/)[1]; // image.jpg

Upvotes: 46

Related Questions