我已经简化了不使用 iFrame 或 flash 引擎上传文件的代码,我想出了这个 ajax 函数:
<input type="file" name="uploadfile" id="myfile" /><label for="file" id="progress"></label>
<script src="js/jquery-1.7.1.min.js"></script>
<script>
function uploadFile(files) {
var xmlhttp;
if(window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.upload.onprogress = function(e) {
$("#progress").empty().append(e.loaded + " - " + e.total);
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText + "DONE!");
}
}
xmlhttp.open("post", "post.php", true);
xmlhttp.setRequestHeader("If-Modified-Since", "Mon, 26 Jul 1997 05:00:00 GMT");
xmlhttp.setRequestHeader("Cache-Control", "no-cache");
xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xmlhttp.setRequestHeader("X-File-Name", files[0].fileName);
xmlhttp.setRequestHeader("Content-Type", "multipart/form-data");
xmlhttp.send(files[0]);
}
$(document).ready(function() {
$("#myfile").change(function() {
uploadFile(this.files);
});
});
</script>
这是回复ajax函数的php代码:
<?php
if(isset(
$_SERVER['CONTENT_TYPE'],
$_SERVER['CONTENT_LENGTH'],
$_SERVER['HTTP_X_FILE_NAME']
) &&
$_SERVER['CONTENT_TYPE'] == 'multipart/form-data'){
$file->name = basename($_SERVER['HTTP_X_FILE_NAME']);
$input = fopen('php://input', 'rb');
$file = fopen('files/'.$file->name, 'wb');
stream_copy_to_stream($input, $file);
fclose($input);
fclose($file);
} else {
echo "Error";
}
?>
问题是,有时它能正常工作,有时它在尝试上传同一文件时出错。我希望有一个解决方案来解决这个问题。代码很简单,当我选择一个输入文件类型的文件时,uploadFile 函数就会执行。 当它出错时,我可以看到文件开始上传,但它没有原始大小,所以它可能在某个地方出错并停止上传。
提前谢谢你,丹尼尔!
最佳答案
我不确定这是你的问题,但无论如何你应该确保你的服务器允许上传足够大的文件并且可以处理它们而不会超时。
您可以在代码或 php.ini 中设置它(代码中的示例:)
ini_set('memory_limit', '96M');
ini_set('post_max_size', '64M');
ini_set('upload_max_filesize', '64M');
然后,确保您的服务器没有超时:
$seconds=120;
set_time_limit ( $seconds );
所有这些代码都在您的 PHP 文件的顶部。
关于php - 没有 iFrame 或 flash 引擎的 ajax php 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9975618/