我有一个文件输入声明如下:
<input id = "front_photo" type = "file" name = "front_photo" onchange = "send_photo()" />
它调用的函数声明如下:
function send_photo ()
{
var fileInput = document.getElementById('front_photo');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('front_photo', file);
console.log("in");
var ajaxHandler = new XMLHttpRequest();
ajaxHandler.onreadystatechange = function ()
{
if(ajaxHandler.readyState == 4)
{
var picture_box = document.getElementById("polaroids_holder");
var adder = document.getElementById("add_polaroid");
var new_pic = document.createElement("div");
new_pic.className = "polaroid";
new_pic.style.backgroundImage = "url('/assets/img/temp_front/"+ajaxHandler.responseText+"')";
picture_box.insertBefore(new_pic, adder);
send_photo();
}
}
ajaxHandler.open('POST', 'upload_polaroid', true);
ajaxHandler.send(formData);
}
选择要上传的文件一次会导致它进入无限循环。我在顶部的“in”堆积在控制台日志中,所以我确定这是函数本身被重复调用,而不是服务器端重定向。此外,正在服务器上创建图像。这是PHP:
function upload_polaroid ()
{
if(isset($_FILES['front_photo']))
{
$format = explode(".", $_FILES["front_photo"]["name"]);
$format = $format[1];
$filename = md5(mt_rand().microtime(true)).".".$format;
$allowedTypes = array("image/tiff", "image/gif", "image/jpeg", "image/png", "image/x-bmp", "image/x-ms-bmp", ".bmp", ".dib", "image/vnd.microsoft.icon", "image/x-xbitmap", "image/x-xbm", ".xbm", ".cur");
if(in_array($_FILES["front_photo"]["type"], $allowedTypes))
{
if(file_exists(getcwd()."/assets/img/temp_front/".$filename))
{
chmod(getcwd()."/assets/img/temp_front/".$filename,0755);
unlink(getcwd()."/assets/img/temp_front/".$filename);
}
move_uploaded_file($_FILES["front_photo"]["tmp_name"], getcwd()."/assets/img/temp_front/".$filename);
$image_path = "/assets/img/temp_front/".$filename;
echo $image_path;
}
else
{
echo "File is not of a valid image type."; die;
}
}
else
die; //var_dump($_FILES);
}
这里可能出了什么问题?