Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  114] [ 6]  / answers: 1 / hits: 15363  / 9 Years ago, sun, march 22, 2015, 12:00:00

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


More From » jquery

 Answers
90

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

[#67350] Thursday, March 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynnb

Total Points: 402
Total Questions: 96
Total Answers: 109

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
kaitlynnb questions
;