最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asmx - How to download file using JavaScript only - Stack Overflow

programmeradmin5浏览0评论

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.

I am getting resume here,

var res = data[i].resume;

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.

I am getting resume here,

var res = data[i].resume;
Share Improve this question edited Apr 15, 2020 at 10:28 AmerllicA 32.5k17 gold badges143 silver badges166 bronze badges asked Nov 12, 2015 at 4:22 amitamit 4495 gold badges8 silver badges21 bronze badges 3
  • Please provide more information about what you are trying to accomplish. Read How to Ask and edit your question accordingly. – Felix Kling Commented Nov 12, 2015 at 4:37
  • It's not javascript, but I think you might still be interested: <form method="get" action="filepath/filename.txt"> <button type="submit">Download!</button> </form> – online Thomas Commented Nov 12, 2015 at 6:50
  • See: stackoverflow.com/a/70969399/10030693 – Gilbert Commented Feb 3, 2022 at 10:15
Add a comment  | 

4 Answers 4

Reset to default 12

You may use different third-party libraries:

jQuery.fileDownload

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

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

Usage:

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

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/
Demo: 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.

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:

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

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.

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

here: 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>

If you use jQuery you can do some like that:

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 getFile and you'll get file content in callback function

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);
    };
}());
发布评论

评论列表(0)

  1. 暂无评论