Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

A, requirements,

For the purpose of the project, when doing a file download, ask for the name of the downloaded file (filename) from the Content-Disposition of Response Headers, via complete() of $.ajax().

$.ajax() complete()

Type: the Function

Callback function after request completion (called after request success or failure).

Parameters: an XMLHttpRequest object and a string describing the type of request.

This is an Ajax event.

Third, concrete implementation

The code is as follows:

/* download(name) {$.ajax({url: "download interface address ", method: "get", // request mode: beforeSend: Function (request) {// Request. SetRequestHeader ("token", sessionStorage.getitem ('token')); Name: name, creator: sessionStorage.getitem ('name')}, success: Function (result) {successData = result}, complete: Function (XHR) {// After the request completes, get fileName, // Console. log(successData) // Get content-disposition let ContentDisposition = in Response Headers Xhr.getresponseheader (' content-disposition ') // fetch fileName Start again from = intercept string fileName = ContentDisposition. Replace (/ "/ g," "). The split (' = ') [1]; // Let uri = 'data:text/ CSV; charset=utf-8,\ufeff' + encodeURIComponent(successData); Let link = document.createElement("a"); let link = document.createElement("a"); link.href = uri; // Name the downloaded file link.download = fileName; document.body.appendChild(link); link.click(); document.body.removeChild(link); }})}Copy the code

Click the “Download” button to Download the react_test1 file

You need to get the filename (filename) as shown:

The file was downloaded successfully with the same filename as filename, as shown in the following figure:

Please feel free to discuss in the comments section. The nuggets will draw 100 nuggets in the comments section after the diggnation project. See the event article for details.