Download Binary Files with Javascript

后端 未结 1 1442
自闭症患者
自闭症患者 2020-12-13 05:01

I want to download binary files using Javascript.

I have a REST service that returns the binary data and i want to know if its possible to show the binary file, whic

相关标签:
1条回答
  • 2020-12-13 05:47

    Have a look at the MDN article on XMLHttpRequest.

    If you set the response of the XMLHttpRequest to ArrayBuffer you could do the following:

    var xhr = new XMLHttpRequest();
    xhr.open("GET", requestUrl);
    xhr.responseType = "arraybuffer";
    
    xhr.onload = function () {
        if (this.status === 200) {
            var blob = new Blob([xhr.response], {type: "application/pdf"});
            var objectUrl = URL.createObjectURL(blob);
            window.open(objectUrl);
        }
    };
    xhr.send();
    

    Option 2:
    You could use Blob as the response of the XMLHttpRequest. And then maybe save it in the FileSystem (FileSystem API)

    It may look like:

    var xhr = new XMLHttpRequest();
    xhr.open("GET", requestUrl);
    xhr.responseType = "blob";
    
    xhr.onload = function () {
        onDownloaded(this);
    };
    xhr.send();
    

    Option 3:
    If you only want to download and "show" images you can easily do this like so:

    var img = new Image();
    
    // add the onload event before setting the src
    img.onload = function() {
        onImageDownloaded(img);
    }
    
    // start the download by setting the src property
    img.src = requestUrl
    
    0 讨论(0)
提交回复
热议问题