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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With