如何使用javascript更改文件名下载?

该脚本为视频添加了下载链接(在特定站点上).下载时如何将文件名更改为其他内容
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,但我尚未在其他浏览器中验证过支持.
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();

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...