如何仅使用 JavaScript 下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33664398/
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 16:45:57  来源:igfitidea点击:

How to download file using JavaScript only

javascriptasmx

提问by amit

I have an only JavaScript page and .asmxpage. I want to download file using only JavaScript how can I download the file. I want to download a particular resume.

我只有一个 JavaScript 页面和.asmx页面。我想仅使用 JavaScript 下载文件如何下载文件。我想下载一份特定的简历。

image

图片

I am getting resume here,

我在这里收到简历,

var res = data[i].resume;

回答by Yeldar Kurmangaliyev

You may use different third-party libraries:

您可以使用不同的第三方库:

jQuery.fileDownload

jQuery.file下载

It takes URL as an input and downloads a file while shows a loading dialog.

它以 URL 作为输入并在显示加载对话框的同时下载文件。

Github: https://github.com/johnculviner/jquery.fileDownload
Demo: http://jqueryfiledownload.apphb.com/

Github:https: //github.com/johnculviner/jquery.file下载
演示:http: //jqueryfiledownload.apphb.com/

Usage:

用法:

$.fileDownload(requestUrl, {
    preparingMessageHtml: "Downloading...",
    failMessageHtml: "Error, please try again."
});

FileSaver.js

文件保护程序

It takes Blobobject as an input and downloads it. Blobcan be acquired using XMLHttpRequest.

它将Blob对象作为输入并下载它。Blob可以使用XMLHttpRequest.

Github: https://github.com/eligrey/FileSaver.js/
Demo: http://eligrey.com/demos/FileSaver.js/

Github:https: //github.com/eligrey/FileSaver.js/
演示:http: //eligrey.com/demos/FileSaver.js/

Usage:

用法:

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();

It may also be used to save canvas-based images, dynamically generated text and any other Blobs.

它还可以用于保存canvas基于图像、动态生成的文本和任何其他Blobs。

Or write it yourself

或者自己写

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

Now, if it is a text file, you can simply download it, create a blob, and save it:

现在,如果它是一个文本文件,您可以简单地下载它,创建一个 blob,然后保存它:

$.ajax({ 
    url: requestUrl,
    processData: false,
    dataType: 'text'
}).done(function(data) {
    var blob = new Blob([data], { type: "text/plain; encoding=utf8" });
    saveData(blob, 'filename.txt');    
});

Or you can use XMLHttpRequestwhich works great for any types of files, including binary:

或者您可以使用XMLHttpRequestwhich 适用于任何类型的文件,包括二进制文件:

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();

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.

这是工作演示。请注意,此小提琴会在打开文件后立即下载文件。该文件只是来自 GitHub 的随机源文件。

回答by Kexin Li

Actually, There is a javascript library called FileSaver.js, FileSaver.js saving file on the client-side. it can help you achieve this.

实际上,FileSaver.js在客户端有一个名为FileSaver.js的 javascript 库保存文件。它可以帮助您实现这一目标。

here: https://github.com/eligrey/FileSaver.js

在这里:https: //github.com/eligrey/FileSaver.js

Usage:

用法:

<script src="http://cdn.jsdelivr.net/g/filesaver.js"></script>
<script>
  function SaveAsFile(t,f,m) {
    try {
      var b = new Blob([t],{type:m});
      saveAs(b, f);
    } catch (e) {
      window.open("data:"+m+"," + encodeURIComponent(t), '_blank','');
    }
  }

SaveAsFile("text","filename.txt","text/plain;charset=utf-8");

</script>

回答by Ashok Baghele

Use the code below.

使用下面的代码。

var sampleBytes = base64ToArrayBuffer('THISISTHETESTDATA');

saveByteArray([sampleBytes], 'ashok.text');

function base64ToArrayBuffer(base64)
 {
    var binaryString =  window.atob(base64);

    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++)
        {
        var ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes;
}

var saveByteArray = (function ()
 {
    var a = document.createElement("a");

    document.body.appendChild(a);

    a.style = "display: none";

    return function (data, name) {

        var blob = new Blob(data, {type: "text/plain"}),

            url = window.URL.createObjectURL(blob);

        a.href = url;
        a.download = name;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

回答by Legotin

If you use jQuery you can do some like that:

如果您使用 jQuery,您可以这样做:

var getFile = function( path_to_file, callback ) {
    $.ajax( {
        url: path_to_file,
        success: callback
    } );
};

getFile( 'path_to_your_asmx_page', function( file_as_text ) {
    console.log( file_as_text );
} );

Call getFileand you'll get file content in callbackfunction

调用getFile,您将在callback函数中获取文件内容