如何使用javascript更改文件名下载? [英] How do I change a filename on-download with javascript?

查看:77
本文介绍了如何使用javascript更改文件名下载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该脚本会为视频添加下载链接(在特定网站上)。下载时如何将文件名更改为其他内容?

The script adds a download link for videos (on a specific site). How do I change the filename to something else while downloading?

Example URL:
"http://website.com/video.mp4"

Example of what I want the filename to be saved as during download:
"The_title_renamed_with_javascript.mp4"


推荐答案

这实际上可以通过JavaScript实现,但浏览器支持会有点不稳定。您可以使用XHR2将文件从服务器下载到浏览器作为Blob,创建Blob的URL,创建一个锚点,将其href属性设置为该URL,将download属性设置为您想要的文件名,然后单击链接。这适用于Google Chrome,但我尚未在其他浏览器中验证支持。

This actually is possible with JavaScript, though browser support would be spotty. You can use XHR2 to download the file from the server to the browser as a Blob, create a URL to the Blob, create an anchor with its href property set to that URL, set the download property to whatever you want the filename to be, and then click the link. This works in Google Chrome, but I haven't verified support in other browsers.

window.URL = window.URL || window.webkitURL;

var xhr = new XMLHttpRequest(),
      a = document.createElement('a'), file;

xhr.open('GET', 'someFile', true);
xhr.responseType = 'blob';
xhr.onload = function () {
    file = new Blob([xhr.response], { type : 'application/octet-stream' });
    a.href = window.URL.createObjectURL(file);
    a.download = 'someName.gif';  // Set to whatever file name you want
    // Now just click the link you created
    // Note that you may have to append the a element to the body somewhere
    // for this to work in Firefox
    a.click();
};
xhr.send();

这篇关于如何使用javascript更改文件名下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆