AJAX POST文件在移动设备上失败

时间:2018-07-16 03:12:57

标签: jquery ajax post

我想通过使用POST方法调用API创建一个表单来上载文档。

它在台式机上确实能很好地运行,但是移动浏览器完全无法执行上传操作。

设备:iPhone X-IOS 11.4

移动浏览器:Google Chrome和Safari(两者均已更新)

HTML代码:

<form id="docsUpload">
    <input type="hidden" name="token" value="aa">
    <input type="file" class="upload-file" id="brFile" name="brFile" data-text="Find file">
    <button id="submitBtn" class="btn btn-custom btn-upload" type="button">
        <span name="langKey">Upload</span>
    </button>
</form>

JQUERY代码:

$('#submitBtn').on('click', function (e) {
    e.preventDefault();
    var data = new FormData($('#docsUpload')[0]);
    var newToken = data.get('token');
    newToken = encodeURIComponent(newToken);

    $.ajax({
        url: host + 'uploadFile?token=' + newToken,
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        enctype: 'multipart/form-data',
        processData: false, // Don't process the files
        contentType: false, // Set content type to false as jQuery will tell the server its a query string request
        success: function (response) {
            console.log(response)
            if (response.isUploadSuccess) {
                return showResult('ok', 'uploadSuccess', response.uploadMessage);
            }
            return showResult('fail', 'uploadFail', response.uploadMessage);
        }, error: function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR);
            let errorMsg = JSON.stringify(jqXHR)
            return showResult('fail', 'uploadFail', errorMsg + '<br>' + textStatus + '<br>' + errorThrown)
        }
    })
});

上面的代码在PC浏览器中完全可以正常工作,但是在移动设备上运行时,我总是收到以下错误:

{"readtState":0,"status":0,"statusText":"error"}

其他信息:

  • ajax URL中的“主机”为https://www.example-A.com,并且JS已加载到https://www.example-B.com中。但是,www.example-A.com Web服务器端已经将Access-Control-Allow-Origin设置为通配符(“ *”)。这就是为什么PC浏览器完全可以正常工作的原因。

我现在完全迷路了。请帮助。

谢谢。

1 个答案:

答案 0 :(得分:0)

我有同样的问题。我无法解决。 我想补充一件事,即使在移动WiFi网络上,它也只能在移动数据上失败。 我确实在同一来源添加了一个页面,并且从服务器端获取了JSON并将其呈现到浏览器,至少这是我解决的问题。