我试图在AJAX的帮助下异步上传图像文件到服务器。该文件通过FIREFOX成功上传,但未通过谷歌浏览器上传。
它显示以下错误消息:Uncaught SyntaxError,意外的输入结束
谷歌搜索它让我有可能错过一两个括号,但我无法在我的代码中找到任何这样的错误。帮助这是代码:
<input type="file" name="profile_image" onchange="uploadedImage(this)"/>
function uploadedImage(image)
{
var file = image.files[0];
var name = file.name;
var size = file.size;
var type = file.type;
var msg='';
if(size>500000)
msg+="File should not be greater than 500kb";
if(type!="image/jpeg")
msg+="Only JPEG images are currently supported";
if(msg!='')
{
alert(msg);
return;
}
var formData = new FormData(document.getElementById('edit_settings'));
$.ajax(
{
url: 'upload_demo_image.php', //Server script to process data
type: 'POST',
xhr: function()
{ // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function(filename)
{
var response = jQuery.parseJSON(filename);
var newImage=response['filename'][0];
$("#edit_profile_image_container").html("<img id='edit_profile_image' src='"+newImage+"' alt='Profile Image'/>");
crop();
}
}
);
}
这是从服务器返回的JSON数据:
{"filename":["uploadDemo\/8_demo.jpg"]}
PHP代码:
<?php session_start();
require_once 'myfunctions.php';
if(isset($_FILES["profile_image"]["name"]))
{
$query="SELECT * FROM students WHERE email='$_SESSION[user]'";
$result=queryMysql($query);
$row=mysql_fetch_array($result);
$_FILES["profile_image"]["name"]=$row['studentid']."_demo.jpg";
$saveto="uploadDemo/$row[studentid]_demo.jpg";
$tempname=$_FILES["profile_image"]["tmp_name"];
$type=$_FILES["profile_image"]["type"];
$image_check=uploadimage($tempname,$saveto,$type,600);
$filename["filename"][]=$saveto;
header('Content-type :text/JSON');
echo json_encode($filename);
}
?>
答案 0 :(得分:0)
header('Content-type :text/JSON');
并在ajax opsions中的js文件中添加:
dataType: 'json',
并删除以下行:
contentType: false,
processData: false,
成功功能删除行:
var response = jQuery.parseJSON(filename);
并创建一个console.log(filename.filename); //第一个'filename'是成功函数的参数,第二个是来自php数组的文件名$ filename [“filename”]
答案 1 :(得分:0)
应该在formData对象中进行更改:
var formData = new FormData();
formData.append("profile_image",filename);
此外,不需要自定义xhr函数。
以上更改可让所有内容都在Chrome中运行。