The json data returned from the uploaded file will be prompted to download the solution

  • 2020-03-30 04:27:12
  • OfStack

Json data returned from the recently uploaded file in the project will be prompted to download, which is only a problem in ie10+. The front end submits the form using jQuery's plug-in, ajaxForm, and the data returned in the background is in json format. The code is as follows:

  The back-end Python:


def jsonp(func):
    """Wraps JSONified output for JSONP requests."""
    @wraps(func)
    def decorated_function(*args, **kwargs):
        callback = request.args.get('callback', False)
        temp_content =  func(*args, **kwargs)
        if isinstance(temp_content, dict):
            temp_content.setdefault('success', True)
            temp_content.setdefault('code', 200)
            try:
                temp_content = json.dumps(temp_content, indent=4)
            except UnicodeDecodeError:
                try:
                  temp_content = ujson.dumps(temp_content)
                except StandardError as e:
                  logger.exception(e)
                  temp_content = json.dumps({'success': False, 'code': 500, 'info': 'INVALID_CONTENT'})
            temp_content = cgi.escape(temp_content)
            if callback:
                # On the basis of http://evilcos.me/?p=425 . jsonp add /**/ The head is safer
                content = '/**/' + str(callback) + '(' + temp_content + ')'
                mimetype = 'application/javascript'
                headers = {'charset':'utf-8'}
                return current_app.response_class(content, mimetype=mimetype,headers=headers)
            else:
                mimetype = 'application/json'
                headers = {'charset':'utf-8'}
                content = temp_content
                return current_app.response_class(content, mimetype=mimetype,headers=headers)
        elif isinstance(temp_content, basestring):
            temp_content = cgi.escape(temp_content)
            return temp_content
        else:
            return temp_content
    return decorated_function
@mod.route('/patch/install.json', methods=['POST'])
@jsonp
def patch_install():
    return {'data': 'data'}

Front-end js code:


$('#form').ajaxSubmit({
    url      : '/patch/install.json',
    type     : 'post',
    dataType : 'json',
    iframe   : true,
    success: function(res) {
        // code
    }
});

Solutions:
The data format returned by the backend needs to be changed to text/ HTML format, as follows:


def plain(func):
    """wrap text/html reponse"""
    @wraps(func)
    def _inner(*args, **kwargs):
        resp = func(*args, **kwargs)
        if isinstance(resp, dict):
            resp.setdefault('success', True)
            resp.setdefault('code', 200)
            resp = json.dumps(resp)
            resp = cgi.escape(resp)
            return current_app.response_class(resp, mimetype='text/html', headers={'charset': 'utf-8'})
        elif isinstance(resp, basestring):
            resp = cgi.escape(resp)
            return current_app.response_class(resp, mimetype='text/html', headers={'charset': 'utf-8'})
        else:
            return resp
    return _inner
@mod.route('/patch/install.json', methods=['POST'])
@plain
def patch_install():
    return {'data': 'data'}

Note: the back end of this example is in Python, if the project encounters the same problem, change to the corresponding language

In summary, the solution to this problem is simply to "change the format of the data returned by the back end to text/ HTML".


Related articles: