我有以下代码通过ajax将文件上传到服务器,它似乎在IE 10和Chrome上工作正常,但在firefox浏览器上没有工作,有什么方法可以解决这个问题吗?下面是所有主流浏览器的代码和输出
$('input.upload').on('change', function(event){
files = event.target.files[0];
uploadFiles(event);
});
function uploadFiles(event)
{
event.stopPropagation();
event.preventDefault();
var form_data = new FormData();
form_data.append('file', files);
//console.log(form_data);
$.ajax({
url: 'uploads.php',
type: 'POST',
data: form_data,
cache: false,
dataType: 'text',
processData: false,
contentType: false, //
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
console.log(data);
}
else
{
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('ERRORS: ' + textStatus);
}
});
}
在我的控制器中,我有以下代码:
public function actionUpload()
{
$upload = new Upload();
$model = new Photos();
$fileName = 'file';
if (isset($_FILES[$fileName])) {
$upload->image = \yii\web\UploadedFile::getInstanceByName($fileName);
$file = $upload->image;
if ($upload->upload()) {
//Now save file data to database
$model->photo1 = $upload->fileDirectory;
if($model->save()){
echo \yii\helpers\Json::encode($file);
}
}
}
return false;
}
在谷歌浏览器和IE浏览器中,ajax中成功方法的console.log(数据)输出如下正确
{"name":"mmexport1370251431731.jpg","tempName":"/tmp/php0UCw4B","type":"image/jpeg","size":36185,"error":0}
在firefox浏览器上,ajax中的success方法的console.log(data)输出如下。只有文件名返回而其他文件属性返回空字符串并返回错误1
{"name":"mmexport1370251431731.jpg","tempName":"","type":"","size":0,"error":1}