The XMLHttpRequest download file method adds an error message that the processing server returns json format

Instructions for this essay

Warning: This article is not suitable for people looking for "XMLHttpRequest download file method" (although my title contains these keywords), this group may be a little ignorant after reading this article.

There is no complete code for downloading files for XMLHttpRequest, only part of the code is extracted to solve specific problems. Because it is extracted from the project, the code also contains some other frameworks used.

 

Problem Description

In the program for downloading files, we are using excel export here. If the server does not have suitable data for export at this time, our original solution is to export an excel that contains only the header column header. Being able to download the file, the user sees a file that does not contain the data he wants, and it will probably be lost, not very user friendly. Then I thought about it, or throw the error prompt into excel, and think about it is still not friendly, so that there are the following improvements:

solution

When there is no suitable data to export or some predictable error occurs, the server returns an error prompt json data. At this time, the front and back ends need to be adjusted as follows.

Use XMLHttpRequest to download files, so set XMLHttpRequest.responseType = "blob", if the server returns a json data, the front end cannot parse out the json data through the general scheme; 
Solution: the server returns a specific http status code When the status code is reached, special processing is performed.
The backend returns a 206 error code and a json data
       // In order to explain the problem more clearly, all other codes are removed here, and only the code that returns the error condition is kept 
 public IActionResult GetPBbackDtoPrintListForPB (GetWorkTimeArrangeInput args)
        {

                Response.StatusCode = 206 ;
                 string msg = " No data! Please make sure there is data under the filter conditions! " ;
                 Return Json ( new BizResult () {Success = false , Message = msg});
            }

The part of the front end that processes json cannot be processed with JSON.parse (result) like normal return json data, or directly result.success, because this way the data cannot be obtained, and there will be undefined errors in the operation. You need to use the following method to read from the stream.

            IF ( the this .status === 206) { // handle error 
                var Result = the this .response;
                 IF (result.type === 'file application / JSON' ) {
                     var Reader = new new the FileReader ();
                    reader.readAsText(result, 'utf-8');
                    reader.onload = (e) => {
                        var jsonData = JSON.parse(reader.result);
                        if (!jsonData.success) {
                            $.messager.alert("警告", jsonData.message);
                        }
                    }
                }

 

The relatively complete front-end code, because of the use of other JS frameworks, if you ca n’t use it, you need to remove some of the code, and there are some value-passing packages, the code is too much, and it is scattered everywhere.

    /**
     * Asynchronous downloading of files depends on easyui's progress bar
     *
     */
    downloadAsync: function (method, url, data,contentType, displayfileName, callback) {
        if (!displayfileName)
            displayfileName = '';
        if (!method)
            method = "get";
        method = method.toLowerCase();
        if (!url)
            throw "url mast has value";

        if (method != "post" && method != "get")
            method = "get";
        var xhr = new XMLHttpRequest();

        var sendData = null;
        if (data && (typeof (data) == "object" || typeof (data) == "string")) {
            if (contentType.toLowerCase() ==="application/json") {
                sendData = JSON.stringify(data);
            } else  if (method.toLowerCase () === "get" ) {
                 // parameter appended to url 
                var params;
                 if ( typeof (data) == "string" )
                    params = data;
                else
                    params = $.param(data);
                var ls = url.indexOf(url.length);
                switch (ls) {
                    case "?":
                    case "&":
                        url += params
                        break;
                    default:
                        if (url.indexOf('?') < 0) {
                            url += "?" + params;
                        } else {
                            url += "&" + params;
                        }
                        break;
                }
            } else {
                sendData = $.param(data);
            }
        }
        xhr.open (method, url, true );     // You can also use POST, according to the interface        
        xhr.setRequestHeader ('content-type' , contentType); 
        xhr.responseType = "blob";   // Return type blob 

        $ .messager .progress ({msg: 'Downloading ...', interval: 0 });
         var bar = $ .messager.progress ('bar' );

        // progress event 
        xhr.onprogress = function (ev) {
             if (ev.lengthComputable) {
                progress = ev.loaded / ev.total;
                 // Update progress 
                bar.progressbar ('setValue', parseFloat (progress, 2) * 100 );
            }
        };

        // Define the processing function for request completion 
        xhr.onload = function () {
             // Request completion 
            if ( this .status === 200 ) {
                 // Return 200 
                var blob = this .response;
                 var reader = new FileReader ();
                reader.readAsDataURL (blob);   // Convert to base64, you can directly put a emoji href 
                reader.onload = function (e) {
                     // Conversion is complete, create an a tag for downloading 
                    var a = document.createElement ('a ' );
                     if (! displayfileName || typeof (displayfileName)! =' string ' )
                        displayfileName = new Date().getTime + '.txt';
                    console.log(displayfileName);
                    a.download = displayfileName;
                    a.href = e.target.result;
                    $ ( "body"). append (a);   // Fix firefox cannot click click 
                    a.click ();
                    $(a).remove();
                    if (typeof (callback) == "function")
                        callback();
                };
            }
            the else  IF ( the this .status === 206) { // handle error 
                var Result = the this .response;
                 IF (result.type === 'file application / JSON' ) {
                     var Reader = new new the FileReader ();
                    reader.readAsText(result, 'utf-8');
                    reader.onload = (e) => {
                        var jsonData = JSON.parse(reader.result);
                        if (!jsonData.success) {
                            $.messager.alert("警告", jsonData.message);
                        }
                    }
                }
            }
            else {
                errortitle = "Error" ;
                error = "Export error" ;
                 switch ( this .status) {
                     case 404 :
                        error + = "Page not found" ;
                         break ;
                     case 400 :
                        error + = "Export parameters are incorrect" ;
                         break ;
                     case 500 :
                        error + = "Failed to export data" ;
                         break ;
                     default :
                         break ;
                }
                $.messager.alert(errortitle, error);
            }
            $.messager.progress('close');
        };
        xhr.onreadystatechange = function (ev) {
        }
        // Send ajax request 
        xhr.send (sendData);
    }

 

Guess you like

Origin www.cnblogs.com/stone2012/p/12719972.html