The management background needs to download data reports at any time, and the data must be generated in real time and then converted to excel for download. How to solve this problem? The editor below will share with you a simple method for processing Ajax request binary stream (ajax asynchronous download of files). Let's take a look. I hope it can help you.
Abstract: ajax requests a binary stream (file), converts it to Blob for processing or downloads and saves the file
Requirements
The management background needs to download data reports at any time, and the data must be real-time After generation, it is 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 about implementation methods and better operating experience. They are not needed (to give an example that requires the second method: if the generation is very slow, you need to disable the button during the generation process to prevent continuous generation). You can not use it if you use it. See
Solution
Method 1
If the interface for requesting files can be changed to GET, you can use this method
<a><i></i> 导出</a>
or change it to another method, Use js to dynamically create a tag
<button>导出</button> function download() { var a = document.createElement('a'); var url = 'download/?filename=aaa.txt'; var filename = 'data.xlsx'; a.href=url; a.download = filename; a.click() }
Disadvantages
Cannot use the post method
Cannot disable the button when starting the download and enable the button after the download is completed
Method 2
Many people are saying that the first method is satisfactory. Wrong way
Conventional method, using jquery:
<button>导出</button> function download() { var url = 'download/?filename=aaa.txt'; $.get(url, function (data) { console.log(typeof(data)) blob = new Blob([data]) var a = document.createElement('a'); a.download = 'data.xlsx'; a.href=window.URL.createObjectURL(blob) a.click() }) }
Files saved in this way cannot be opened. Console.log(typeof(data)) will see that it is a string type. The reason is that jquery converts the returned data into string and does not support the blob type.
Correct way
<button>导出</button> function download() { var url = 'download/?filename=aaa.txt'; var xhr = new XMLHttpRequest(); xhr.open('GET', 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('a'); a.download = 'data.xlsx'; a.href = e.target.result; $("body").append(a); // 修复firefox中无法触发click a.click(); $(a).remove(); } } }; // 发送ajax请求 xhr.send() }
Related recommendations:
The above is the detailed content of Simple way to download files asynchronously with Ajax. For more information, please follow other related articles on the PHP Chinese website!

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingclassesfromtheirdependencies.1)UseConstructorInjectiontopassdependenciesviaconstructors,ensuringfullinitialization.2)EmploySetterInjectionforpost-creationdependencychanges,t

Pimple is recommended for simple projects, Symfony's DependencyInjection is recommended for complex projects. 1)Pimple is suitable for small projects because of its simplicity and flexibility. 2) Symfony's DependencyInjection is suitable for large projects because of its powerful capabilities. When choosing, project size, performance requirements and learning curve need to be taken into account.

DependencyInjection(DI)inPHPisadesignpatternwhereclassdependenciesarepassedtoitratherthancreatedinternally,enhancingcodemodularityandtestability.Itimprovessoftwarequalityby:1)Enhancingtestabilitythrougheasydependencymocking,2)Increasingflexibilitybya


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
