我有一个文件上传功能,并使用
html5中的slice api,我将每个文件切成1MB块,但最终结果导致文件被破坏.有时,最终结果比原始文件小,有时即使它是正确的大小,我仍然无法打开它.有谁有任何想法?或解决方案?
这是切片的一部分
var uploaders = [];
var i = 0;
$(document).ready(function() {
var progress = document.querySelector('progress');
var bars = document.querySelector('#bars');
});
//function for after the button is clicked, slice the file
//and call upload function
function sendRequest() {
//clean the screen
bars.innerHTML = '';
var blob = document.getElementById('fileToUpload').files[0];
var originalFileName = blob.name;
const BYTES_PER_CHUNK = 1 * 1024 * 1024; // 10MB chunk sizes.
const SIZE = blob.size;
var start = 0;
var end = BYTES_PER_CHUNK;
while( start < SIZE ) {
if (blob.webkitSlice) {
var chunk = blob.webkitSlice(start, end);
} else if (blob.mozSlice) {
var chunk = blob.mozSlice(start, end);
}
uploadFile(chunk, originalFileName);
start = end;
end = start + BYTES_PER_CHUNK;
}
}
function uploadFile(blobFile, fileName) {
var progress = document.createElement('progress');
progress.min = 0;
progress.max = 100;
progress.value = 0;
bars.appendChild(progress);
var fd = new FormData();
fd.append("fileToUpload", blobFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.php"+"?"+"file="+fileName + i, true);
i++;
xhr.onload = function(e) {
//make sure if finish progress bar at 100%
progress.value = 100;
//counter if everything is done using stack
uploaders.pop();
if (!uploaders.length) {
bars.appendChild(document.createElement('br'));
bars.appendChild(document.createTextNode('DONE :)'));
}
};
// Listen to the upload progress for each upload.
xhr.upload.onprogress = function(e) {;
if (e.lengthComputable) {
progress.value = (e.loaded / e.total) * 100;
}
};
uploaders.push(xhr);
xhr.send(fd);
}
这是用于接受二进制块的php文件
$target_path = "uploads/";
$tmp_name = $_FILES['fileToUpload']['tmp_name'];
$size = $_FILES['fileToUpload']['size'];
$name = $_FILES['fileToUpload']['name'];
$originalName = $_GET['file1'];
print_r("*******************************************\n");
print_r($originalName);
print_r("\n");
print_r($_FILES);
print_r("\n");
print_r("*******************************************\n");
$target_file = $target_path . basename($name);
//Result File
$complete = $originalName;
$com = fopen("uploads/".$complete, "ab");
error_log($target_path);
if ( $com ) {
// Read binary input stream and append it to temp file
$in = fopen($tmp_name, "rb");
if ( $in ) {
while ( $buff = fread( $in, 1048576 ) ) {
fwrite($com, $buff);
}
}
fclose($in);
fclose($com);
}
?>
我认为我在使用我的PHP代码将文件放在服务器上时做错了(就像我没有按顺序或其他东西),但是有人知道如何做到这一点或最佳做法可能吗?而不是上传文件然后将其组合,可能先将其保存在内存中,然后再将其写入文件.