在下载文件出错的情况下,管理表单提交上的JSON服务器响应

Manage JSON server response on form submit in case of error downloading file

本文关键字:表单提交 JSON 响应 服务器 管理 下载 文件 出错 情况下      更新时间:2023-09-26

我有一个简单的jQuery代码,当用户点击按钮时,它会要求PHP服务器下载文件:

// Build a temp form
var jRestr = {sFitxer: sFitxer, bDownload: true};
var $form = $('<form></form>').attr('action', getMBD_URL()).attr('method', 'post');
// Add the one key/value
$form.append($("<input></input>").attr('type', 'hidden').attr('name', 'Consulta').attr('value', 'downLoadFile.php'));
$form.append($("<input></input>").attr('type', 'hidden').attr('name', 'UserName').attr('value', sessionStorage.usuari));
$form.append($("<input></input>").attr('type', 'hidden').attr('name', 'Token').attr('value', sessionStorage.token));
$form.append($("<input></input>").attr('type', 'hidden').attr('name', 'sFormat').attr('value', 'META'));
$form.append($("<input></input>").attr('type', 'hidden').attr('name', 'Modul').attr('value', sModul_glb));
$form.append($("<input></input>").attr('type', 'hidden').attr('name', 'sjRestr').attr('value', JSON.stringify(jRestr)));
//send request
$form.appendTo('body').submit().remove();

这很有魅力,但如果服务器遇到一些问题(找不到文件、权限被拒绝等(,它会返回一个带有错误信息的JSON,而不是请求的文件。

我如何捕捉它并以用户可读的格式显示它?

我不知道我可以使用哪种技术,因为如果我使用AJAX调用,我不知道如何下载文件,如果我使用HTML提交调用,我将失去响应控制。

主要问题是您无法使用ajax下载文件,除非您将文档重定向到的某个位置(使用JSwindow.location提交的表单(。

"正确"的方式

在服务器中创建一个端点,以检查文件是否存在(或是否具有使用ajax轻松访问的权限等(,一旦该请求得到成功响应,则重定向(提交创建的表单(以获取文件。

var url = "new_endpoint_to_check_if_file_exists";
$.ajax({
    url: url,
    type: 'GET',
    success: function() {
        // Here the code to append your form and submit to download file.
    },
    error: function(er){
       console.log(er);
    }
});

另一方面,如果您想控制响应,我们鼓励您使用Ajax,因此请修改服务器上的逻辑工作方式。

丑陋的方式

如果你不能像前面提到的那样修改响应的逻辑工作方式,那么理论上你仍然可以下载文件,但你需要对同一个URL发出两次请求(提交两次表单(。

// The form Data
var data = {
    'Consulta': 'downLoadFile.php',
    'UserName': sessionStorage.usuari,
    'Token': sessionStorage.token,
    'sFormat': 'META',
    'Modul': sModul_glb,
    'sjRestr' JSON.stringify(jRestr)
};
// The request URL 
var url = getMBD_URL();
$.ajax({
    url: ,
    type: 'POST',
    data: data
    success: function() {
        // If the "file exists or there's no server error"
        // Generate the file download again
        // Build the form and submit again ...
        var jRestr = {sFitxer: sFitxer, bDownload: true};
        var $form = $('<form></form>').attr('action', getMBD_URL()).attr('method', 'post');
        // Add the one key/value
        $form.append($("<input></input>").attr('type', 'hidden').attr('name', 'Consulta').attr('value', 'downLoadFile.php'));
        $form.append($("<input></input>").attr('type', 'hidden').attr('name', 'UserName').attr('value', sessionStorage.usuari));
        $form.append($("<input></input>").attr('type', 'hidden').attr('name', 'Token').attr('value', sessionStorage.token));
        $form.append($("<input></input>").attr('type', 'hidden').attr('name', 'sFormat').attr('value', 'META'));
        $form.append($("<input></input>").attr('type', 'hidden').attr('name', 'Modul').attr('value', sModul_glb));
        $form.append($("<input></input>").attr('type', 'hidden').attr('name', 'sjRestr').attr('value', JSON.stringify(jRestr)));
        //send request
        $form.appendTo('body').submit().remove();
    },
    error: function(er){
       console.log(er);
    }
});

这应该会奏效,然而,我会选择"正确"的方式。

Ajax不是用来下载文件的。相反,您可以只获取响应中的文件名,然后将其重定向到

ajax的成功函数是这样的。

document.location = "download.php?filename=" + response.fileName;

其余的工作将由php通过这两个头进行响应。

下载.php

<?php 
$filename = $_GET['filename'];
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename=' . $filename);