javascript 如何通过 URL 下载文件然后获取其名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29192301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:12:40  来源:igfitidea点击:

How to download a file via URL then get its name

javascriptjquery

提问by HarryJ2213

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.

这是我用 JS+jQuery 制作的用户脚本。我想知道是否有可能找到给定 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".

然后该链接会下载一个文件,例如“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).

我愿意使用任何 JS 库 - 但我需要确保该文件实际上并未保存在用户计算机中(或者它可能只是保存在某个临时文件夹中)。

回答by dfsq

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-Dispositionheader which contains filenamefield.

您可以做的最简单的事情是发出 HEAD 请求,这样您就不会实际下载文件,而只会下载响应标头。从那里你得到Content-Disposition包含filename字段的标题。

Something like this in jQuery:

在 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);
    }
});

headervariable will be something like attachment; filename="image.jpg". Now it's easy to extract filename part:

header变量将类似于attachment; filename="image.jpg". 现在很容易提取文件名部分:

var filename = header.match(/filename="(.+)"/)[1]; // image.jpg