这是问题的切线:
Returning value to Javascript from PHP called from XMLHttpRequest
我正在为我的AjaxChat添加一个“图像上传”按钮。我正在使用XMLHttpRequest将图像发送到服务器,在那里我运行PHP脚本将其移动到我的images文件夹。下面是负责打开XMLHttpRequest连接并发送文件的Javascript函数:
function uploadImage() {
var form = document.getElementById('fileSelectForm');
var photo = document.getElementById('photo');
var uploadButton = document.getElementById('imageUploadButton');
form.onsubmit = function(event) {
event.preventDefault();
// Update button text
uploadButton.innerHTML = 'Uploading...';
//Get selected files from input
var files = photo.files;
// Create a new FormData object
var formData = new FormData();
// Loop through selected files
for (var i = 0; files.length > i; i++) {
var file = files[i];
// Check file type; only images are allowed
if (!file.type.match('image/*')) {
continue;
}
// Add file to request
formData.append('photo', file, file.name);
}
// Set up request
var xhr = new XMLHttpRequest();
// Open connection
xhr.open('POST', 'sites/all/modules/ajaxchat/upload.php', true);
// Set up handler for when request finishes
xhr.onload = function () {
if (xhr.status === 200) {
//File(s) uploaded
uploadButton.innerHTML = 'Upload';
var result = xhr.responseText;
ajaxChat.insertText('\n\[img\]http:\/\/www.mysite.com\/images' + result + '\[\/img\]');
ajaxChat.sendMessage();
} else {
alert('An error occurred!');
}
form.reset();
};
// Send data
xhr.send(formData);
}
}
这是upload.php:
<?php
$valid_file = true;
if($_FILES['photo']['name']) {
//if no errors...
if(!$_FILES['photo']['error']) {
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) { //can't be larger than 1 MB
$valid_file = false;
}
//if the file has passed the test
if($valid_file) {
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], '/var/www/html/images'.$new_file_name);
$message = $new_file_name;
exit("$message");
}
}
}
?>
我目前禁用了多个图片上传,因此“循环选定文件”只执行一次。
上传在我的电脑上工作了一点,但后来我尝试从手机上传图像。当我这样做时,整个服务器(和我的浏览器)崩溃了,大概是由于某个地方的无限循环。每次我关闭浏览器并重新登录,或重新启动服务器,或重新启动计算机时,它都会挂起并最终再次崩溃(在我的电脑或手机上)。我一直无法找到导致问题的脚本。我觉得它在我的鼻子底下。有谁看到这个问题?如果您需要HTML表单代码,那么我可以提供,但我不认为这是必要的。