How to download file using JavaScript only

南楼画角 提交于 2019-12-10 10:05:42

问题


I have only JavaScript page and .asmx page.I want to download file using only JavaScript how can I download the file please give some solution. I am beginner in JavaScript. I want to download particular resume.

http://i.stack.imgur.com/HW921.jpg

I am getting resume here,

var res = data[i].resume;

I want to download resume please help me.


回答1:


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.




回答2:


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>



回答3:


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




回答4:


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


来源:https://stackoverflow.com/questions/33664398/how-to-download-file-using-javascript-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!