Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 420
HarryJ2213 Avatar asked Mar 22 '15 08:03

HarryJ2213


People also ask

How do I get the filename in a URL?

The filename is the last part of the URL from the last trailing slash. For example, if the URL is http://www.example.com/dir/file.html then file. html is the file name.


1 Answers

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
like image 134
dfsq Avatar answered Oct 27 '22 02:10

dfsq