如何仅使用JavaScript下载文件 [英] How to download file using JavaScript only
问题描述
我只有一个JavaScript页面和.asmx
页面.我要下载文件
仅使用JavaScript如何下载文件.我要下载特定的简历.
I have an only JavaScript page and .asmx
page. I want to download file
using only JavaScript how can I download the file. I want to download a particular resume.
我在这里得到简历,
var res = data[i].resume;
推荐答案
您可以使用其他第三方库:
You may use different third-party libraries:
它以URL作为输入并下载文件,同时显示一个加载对话框.
It takes URL as an input and downloads a file while shows a loading dialog.
Github: https://github.com/johnculviner/jquery.fileDownload
演示: http://jqueryfiledownload.apphb.com/
Github: https://github.com/johnculviner/jquery.fileDownload
Demo: http://jqueryfiledownload.apphb.com/
用法:
$.fileDownload(requestUrl, {
preparingMessageHtml: "Downloading...",
failMessageHtml: "Error, please try again."
});
FileSaver.js
它将Blob
对象作为输入并下载.可以使用XMLHttpRequest
获取Blob
.
FileSaver.js
It takes Blob
object as an input and downloads it. Blob
can be acquired using XMLHttpRequest
.
Github: https://github.com/eligrey/FileSaver.js/
演示: http://eligrey.com/demos/FileSaver.js/
Github: https://github.com/eligrey/FileSaver.js/
Demo: http://eligrey.com/demos/FileSaver.js/
用法:
var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "blob";
xhr.onload = function () {
saveAs(this.response, 'filename.txt'); // saveAs is a part of FileSaver.js
};
xhr.send();
它还可用于保存基于canvas
的图像,动态生成的文本和任何其他Blob
.
It may also be used to save canvas
-based images, dynamically generated text and any other Blob
s.
function saveData(blob, fileName) // does the same as FileSaver.js
{
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
}
现在,如果它是文本文件,则只需下载,创建Blob并保存即可:
Now, if it is a text file, you can simply download it, create a blob, and save it:
$.ajax({
url: requestUrl,
processData: false,
dataType: 'text'
}).done(function(data) {
var blob = new Blob([data], { type: "text/plain; encoding=utf8" });
saveData(blob, 'filename.txt');
});
或者您可以使用XMLHttpRequest
,它对任何类型的文件都适用,包括二进制文件:
Or you can use XMLHttpRequest
which works great for any types of files, including binary:
var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "blob";
xhr.onload = function () {
saveData(this.response, 'filename'); // saveAs is now your function
};
xhr.send();
这是工作演示.请注意,此小提琴在打开文件后立即下载文件.该文件只是来自GitHub的随机源文件.
Here is the working demo. Note that this fiddle downloads a file right after opening it. The file is just a random source file from GitHub.
这篇关于如何仅使用JavaScript下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!