[英]Large file uploads using FileReader and php
我目前正在為非常大的文件(比服務器允許的更大)開發一個上傳模塊,並帶有進度和所有這些東西。 請參閱下面的代碼。 它適用於文本文件、圖像,甚至 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 中的結果。 請指教
這只是黑暗中的一個鏡頭,但查看 file.slice API ( http://www.w3.org/TR/FileAPI/#dfn-slice ),它說:
“slice 方法返回一個新的 Blob 對象,其字節范圍從可選的開始參數到但不包括可選的結束參數,並且具有一個類型屬性,它是可選的 contentType 參數的值。”
但是,在使用它之前從“end”中減去 1 - 這是否意味着您在每個chunk
留下 1 個字節(因為無論如何都不包括結束字節)?
另外,您在使用$_POST['filename']
之前確實對其進行了消毒 - 不是有人將"../yourscript.php"
放在那里?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.