我目前正在为非常大的文件(比服务器允许的更大)开发一个上传模块,其中包含进度和所有这些东西。请参阅下面的代码。它适用于文本文件、图像,甚至 doc 和 pdf 文件。对于任何其他文件类型,它都会崩溃。有人有什么建议吗?
var fr = new FileReader;
chunkSize = 524288;
//chunkSize = window.maxPost;
var chunks = Math.ceil(file.size / chunkSize);
var chunk = 0;
function SendSlice() {
var start, end;
start = chunk * chunkSize;
if (start > file.size) {
start = end + 1;
}
end = start + (chunkSize - 1) >= file.size ? file.size : start + (chunkSize - 1);
status = chunk == 0 ? "start" : (chunk == chunks ? "end" : "progress");
if (status == 'start') {
$("#upload-area").append("<p>Upload started for file " + file.name + "</p>");
}
fr.onload = function(e) {
var sliceData = e.target.result;
$.ajax({
type : "POST",
url : "uploader.php",
data : {
filename : file.name,
status : status,
slice : sliceData
}
}).success(function(data) {
if (++chunk <= chunks) {
SendSlice();
var progress = (chunk / chunks) * 100;
$("#progress-text").html(progress.toFixed(2) + "%");
$("#progress").css({
width : progress + "%"
});
} else {
$("#upload-area").append("<p>File " + file.name + " uploaded succesfully. Download file <a target='_blank' href='uploads/" + file.name + "'>here</a></p>");
}
});
};
fr.readAsDataURL(file.slice(start, end));
}
SendSlice();
和PHP代码:
if($_POST['status'] == 'start') {
if (file_exists("uploads/" . $_POST['filename'])) {
unlink("uploads/" . $_POST['filename']);
}
}
$data = explode(",", $_POST['slice']);
$data = $data[1];
$data = base64_decode($data);
file_put_contents("uploads/" . $_POST['filename'], $data, FILE_APPEND);
另外,我尝试过使用 readAsBinaryString,但我不知道如何在 PHP 中处理结果。请指教