Ajax can’t download file to browser

Recently, I encountered such a function when I was working on a website. In the page as shown in the figure, when users need to click the link, they can judge whether the corresponding excel file is stored in the server in an asynchronous ajax way. If not, they will be prompted that they have not found it, and if so, they will download it to the local user.

 

Of course, this is a very simple problem. Just write Ajax in a normal way. But when the server returns the file content to the browser in binary form, the browser’s Ajax throws an error. It’s about parseError, invalid XML, PK, etc.

 

 

The reason for this problem is not that there is a problem with the server-side code or JavaScript code, but that downloading files through AJAX is forbidden. For security reasons, JavaScript is not able to save the file to the local, so Ajax takes this into account. It only accepts the return value in XML, Ajax and JSON format, and the binary return format will throw this exception.

 

How to solve this problem?use window.location =URL is OK. Some people will ask, such as the above figure, when you click the download link on a certain page, because it has changed window.location Is the current page about to jump?In fact, I use Chrome browser. When I click that link, the next file save dialog box will pop up directly, and the address bar of the page has no change. At this time, if you click save, the file will be kept. If you click cacel, the operation will be cancelled. During the process, the current page will be kept and will not jump to other pages.

 

 

From personal blog www.sunrobin.net

 

 

Read More: