我正在尝试制作一个带有进度条的ajax上传功能,我试图简化我在互联网上找到的一个例子,我得到了这个功能:
<form>
<input type="file" id="file" /><label for="file"></label><label id="aaa"></label>
<button id="sub">abc</button>
</form>
<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) {
$("#aaa").empty().append(e.loaded + " - " + e.total);
}
xmlhttp.upload.onload = function(e) {
$("#aaa").empty().append("finish");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
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("X-File-Size", files[0].fileSize);
xmlhttp.setRequestHeader("Content-Type", "multipart/form-data");
xmlhttp.send(files[0]);
}
$(document).ready(function() {
$("#file").change(function() {
uploadFile(this.files);
});
});
</script>
当我上传接近或低于800kb-1MB的文件时,它工作得很好,速度很快,但当我试图上传更大的文件时它会出错。进度条显示它正在上传,但onreadystatechange不会触发,文件也不会出现在服务器上。
回复这个ajax的php是这样的:
<?php
// e.g. url:"page.php?upload=true" as handler property
//print_r($_SERVER);
if(
// basic checks
isset(
$_SERVER['CONTENT_TYPE'],
$_SERVER['CONTENT_LENGTH'],
$_SERVER['HTTP_X_FILE_NAME']
) &&
$_SERVER['CONTENT_TYPE'] == 'multipart/form-data'
){
// create the object and assign property
/*$file = new stdClass;
$file->name = basename($_SERVER['HTTP_X_FILE_NAME']);
$file->size = $_SERVER['HTTP_X_FILE_SIZE'];
$file->content = file_get_contents("php://input");
// if everything is ok, save the file somewhere
if(file_put_contents('files/'.$file->name, $file->content))
echo "OK";*/
$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 {
// if there is an error this will be the output instead of "OK"
echo "Error";
}
?>
提前谢谢你,丹尼尔!
查看服务器变量:
- 最大文件大小
- 上传最大文件大小
- post_max_size
- 内存限制
http://php.net/manual/en/features.file-upload.post-method.php
这些变量可能有一些限制。
问候!