如何通过URL下载文件然后获取其名称 [英] How to download a file via URL then get its name
问题描述
这是我用JS + jQuery制作的用户脚本。我想知道是否可以找到给定URL的文件名。
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.
它的形式为:
http://example.org/download.php?action=download&id=1234
然后该链接下载一个文件,例如cat.jpg。
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.
我愿意使用任何JS库 - 但我需要确保文件实际上没有保存在用户计算机中(或者它可能只保存在一个临时文件夹)。
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).
推荐答案
你可以做的简单事情是提出HEAD请求,这样你就不会下载文件但只有响应标头。从那里你得到 Content-Disposition
标题,其中包含 filename
字段。
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.
jQuery中有类似的东西:
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
变量将类似附件;文件名= image.jpg的
。现在提取文件名部分很容易:
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
这篇关于如何通过URL下载文件然后获取其名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!