我正在使用FormData和jQuery的ajax来上传表单文件。 一切正常,除非在iOS上没有选择任何文件,然后从PHP脚本收到错误500。
在PC和Android上,无论是否选择了文件,它都可以正常工作,但是在iOS上,只有选择了文件后,它才可以工作(不需要选择文件)。 我正在使用最新的iOS 11.4.1。
这是提交表单时调用的我的代码:
var form = this;
var data = new FormData(form);
var options = {
url: $(form).attr('action'),
data: data,
type: $(form).attr('method'),
cache: false,
contentType: false,
processData: false,
complete: function(r){
if(r.status == 200){
var response = r.responseJSON;
showErrors(form, response.errors);
$.each(response.actions, handleAction.bind(form));
}else{
showErrors(form, ['Vyskytla sa neočkávaná chyba, skúste znova neskôr']);
}
}
};
if(data.fake){
opts.xhr = function(){
var xhr = jQuery.ajaxSettings.xhr();
xhr.send = xhr.sendAsBinary;
return xhr;
}
opts.contentType = 'multipart/form-data;boundary='+data.boundary;
opts.data = data.toString();
}
$.ajax(options);
有一部分代码打印了服务器的响应,这就是响应:
{"readyState":4,"responseText":"\n\n\n\n
Internal Server Error
\n
The server encountered an internal error or\nmisconfiguration and was unable to complete\nyour request.
\n
Please contact the server administrator at \n ssl@atlantis.sk to inform them of the time this error occurred,\n and the actions you performed just before this error.
\n
More information about this error may be available\nin the server error log.
\n\n","status":500,"statusText":"Internal Server Error"}
答案 0 :(得分:1)
我终于找到了解决我问题的方法,它不在服务器端。 看起来FormData将iOS上一个空File对象的数组放入数据变量中,服务器无法处理该变量。
我为此编辑了JS:
var data = new FormData(form);
$.each($(form).find('input[type="file"]'), function(){
var name = $(this).attr('name');
var files = $(this).prop('files');
if(files.length == 0){
data.set(name, null);
}
});