Home Web Front-end JS Tutorial Ajax request binary stream for processing (ajax asynchronous download file)

Ajax request binary stream for processing (ajax asynchronous download file)

May 22, 2018 am 09:19 AM
ajax binary deal with

ajax requests a binary stream (file), converts it to Blob for processing or downloads and saves the file

Requirements

The management background needs to be done at any time Download the data report. The data must be generated in real time and then converted to excel for download.

The file is not large. There is an "Export" button on the page. After clicking the button, a save file dialog box will pop up. The two methods are purely talking about the implementation method and better operating experience. They are not needed (to give an example where the second method is needed: if the generation is very slow, you need to disable the button during the generation process to prevent continuous generation). If you use it, you can not use it. See

Solution

Method 1

The interface for requesting files can be changed to GET then You can use this method

<a class="btn btn-primary btn-xs" download="data.xlsx" href="download/?filename=aaa.txt" rel="external nofollow" ><i class="fa fa-share-square-o fa-lg"></i> 导出</a>
Copy after login

or change it to another way and use js to dynamically create a tag

<button type="button" onclick="download()">导出</button>
function download() {
  var a = document.createElement(&#39;a&#39;);
  var url = &#39;download/?filename=aaa.txt&#39;;
  var filename = &#39;data.xlsx&#39;;
  a.href=url;
  a.download = filename;
  a.click()
 }
Copy after login

Disadvantages The post method cannot be used

You cannot disable the button when starting the download and enable the button after the download is completed

Method 2

Many people are talking about the first method The method can be satisfied. Error method

Conventional method, use jquery:

<button type="button" onclick="download()">导出</button>
function download() {
  var url = &#39;download/?filename=aaa.txt&#39;;
  $.get(url, function (data) {
    console.log(typeof(data))
    blob = new Blob([data])
    var a = document.createElement(&#39;a&#39;);
    a.download = &#39;data.xlsx&#39;;
    a.href=window.URL.createObjectURL(blob)
    a.click()
  })
}
Copy after login

Files saved in this way cannot be opened. Console.log(typeof(data)) will see that it is string Type, the reason is that jquery converts the returned data into string and does not support the blob type.

Correct way

<button type="button" onclick="download()">导出</button>
function download() {
  var url = &#39;download/?filename=aaa.txt&#39;;
  var xhr = new XMLHttpRequest();
  xhr.open(&#39;GET&#39;, url, true);    // 也可以使用POST方式,根据接口
  xhr.responseType = "blob";  // 返回类型blob
  // 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
  xhr.onload = function () {
    // 请求完成
    if (this.status === 200) {
      // 返回200
      var blob = this.response;
      var reader = new FileReader();
      reader.readAsDataURL(blob);  // 转换为base64,可以直接放入a表情href
      reader.onload = function (e) {
        // 转换完成,创建一个a标签用于下载
        var a = document.createElement(&#39;a&#39;);
        a.download = &#39;data.xlsx&#39;;
        a.href = e.target.result;
        $("body").append(a);  // 修复firefox中无法触发click
        a.click();
        $(a).remove();
      }
    }
  };
  // 发送ajax请求
  xhr.send()
}
Copy after login
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How the Django framework uses the ajax post method (graphic tutorial)

django obtains the ajax post complex object Method (graphic tutorial)

About the problem of passing data in the background through response in Ajax (including code, detailed analysis)

The above is the detailed content of Ajax request binary stream for processing (ajax asynchronous download file). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The operation process of WIN10 service host occupying too much CPU The operation process of WIN10 service host occupying too much CPU Mar 27, 2024 pm 02:41 PM

1. First, we right-click the blank space of the taskbar and select the [Task Manager] option, or right-click the start logo, and then select the [Task Manager] option. 2. In the opened Task Manager interface, we click the [Services] tab on the far right. 3. In the opened [Service] tab, click the [Open Service] option below. 4. In the [Services] window that opens, right-click the [InternetConnectionSharing(ICS)] service, and then select the [Properties] option. 5. In the properties window that opens, change [Open with] to [Disabled], click [Apply] and then click [OK]. 6. Click the start logo, then click the shutdown button, select [Restart], and complete the computer restart.

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

Learn how to handle special characters and convert single quotes in PHP Learn how to handle special characters and convert single quotes in PHP Mar 27, 2024 pm 12:39 PM

In the process of PHP development, dealing with special characters is a common problem, especially in string processing, special characters are often escaped. Among them, converting special characters into single quotes is a relatively common requirement, because in PHP, single quotes are a common way to wrap strings. In this article, we will explain how to handle special character conversion single quotes in PHP and provide specific code examples. In PHP, special characters include but are not limited to single quotes ('), double quotes ("), backslash (), etc. In strings

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to read binary files in Golang? How to read binary files in Golang? Mar 21, 2024 am 08:27 AM

How to read binary files in Golang? Binary files are files stored in binary form that contain data that a computer can recognize and process. In Golang, we can use some methods to read binary files and parse them into the data format we want. The following will introduce how to read binary files in Golang and give specific code examples. First, we need to open a binary file using the Open function from the os package, which will return a file object. Then we can make

Can Golang handle binary files? Can Golang handle binary files? Mar 20, 2024 pm 04:36 PM

Can Golang handle binary files? In Go language, processing binary files is very common and convenient. By using built-in packages and methods we can easily read, write and manipulate binary files. This article explains how to handle binary files in Go and provides specific code examples. Reading Binary Files To read a binary file, we first need to open the file and create a corresponding file object. We can then use the Read method to read the data from the file and store it in bytes in

See all articles