我托管了一个视频文件,如下所示:
https://cdn.shopify.com/s/files/1/0664/3037/0044/files/video
目前,视频文件根本没有扩展名。使用 Javascript,如何下载扩展名为 .mp4 的文件。我需要一种方法将其文件名更改为 [文件名].mp4,然后下载。
我尝试了以下操作,但它下载的文件没有扩展名。
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
downloadURI("https://cdn.shopify.com/s/files/1/0664/3037/0044/files/video", "video.mp4");
最佳答案
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-download
download
only works for same-origin URLs, or the blob: and data: schemes. If theContent-Disposition
header has different information from the download attribute, resulting behavior may differ:If the header specifies a filename, it takes priority over a filename specified in the
download
attribute.
If the header specifies a disposition ofinline
, Chrome and Firefox prioritize the attribute and treat it as a download. Old Firefox versions (before 82) prioritize the header and will display the content inline.
我在不同的源上尝试了你的代码,但它不会下载,只是重定向到 URL,它也不会发送 Content-Disposition
,所以看起来你正在测试这在不同的源上,它只是重定向到文件链接,丢弃 download
因为它在不同的源上,并且您的浏览器配置为下载它。我的浏览器配置为自动播放视频。
但是,我看到您提供的 URL 具有 CORS *,这意味着任何来源都可以访问它。因此,您可以做的另一种选择是下载文件并创建一个 blob,然后将下载内容发送到浏览器。
function downloadURI(uri, name) {
fetch(uri).then((response) => response.blob())
.then((blobresp) => {
var blob = new Blob([blobresp], {type: "octet/stream"});
var url = window.URL.createObjectURL(blob);
var link = document.createElement("a");
link.download = name;
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
})
}
downloadURI("https://cdn.shopify.com/s/files/1/0664/3037/0044/files/video", "video.mp4");
关于javascript - 如何在下载前更改文件的扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74185498/