11

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

HarryJ2213
  • 113
  • 1
  • 1
  • 5
  • I assume you're doing this with an AJAX call. That information would be only be provided in the `Response Header` which you can get from the method in this guy's post http://stackoverflow.com/questions/1557602/jquery-and-ajax-response-header So you will make an AJAX call to initiate the download, get the response headers, parse them for the filename, then terminate the AJAX call as soon as you get what you want. Unless you have control over the `download.php` file and can add the functionality to provide only the filename by download `id` without downloading the file, this is the only way. – FactoryAidan Mar 22 '15 at 08:26

1 Answers1

39

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
dfsq
  • 182,609
  • 24
  • 222
  • 242