我尝试使用Resumable Uploads模式实现ng-file-upload以分块大文件并在上传后合并它们。我在许多项目中实现了ng-file-upload,但这是我第一次上传这么大的文件。
我的问题是我不知道如何使它在PHP中使用服务器端文件。我只需要上传不同名称的块,但我无法将它们合并。
有人可以在PHP中发布一个服务器端代码示例来使这项功能正常工作吗?
这就是我到目前为止所做的:
AngularJS
$scope.uploadMediaFile = function (file) {
if(file) {
Upload.upload({
ignoreLoadingBar: true,
url: 'app/api/upload/mediaFile.php',
resumeChunkSize: '1MB',
file: file
}).then(function (response) {
if(response.data.success) {
$scope.post.mediaFile = response.data.filename;
$scope.post.duration = response.data.duration;
} else {
console.error(response.data.error);
}
}, null, function (evt) {
console.log(part);
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
};
mediaFile.php
$filename = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_ext = pathinfo($filename, PATHINFO_EXTENSION);
$file_des = $_SERVER['DOCUMENT_ROOT'] . '/storage/content/temp/';
if(!file_exists($file_des)) mkdir($file_des);
// Puting a diferent name for each file part
$new_filename = uniqid() . "." . pathinfo($filename, PATHINFO_EXTENSION);
move_uploaded_file($file_tmp, $file_des . $new_filename)
到目前为止,我收到了许多具有不同名称的相同文件。
答案 0 :(得分:1)
如果有人看到类似的问题,我会发布我的解决方案。
<?php
// File chunk
$filename = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
// Defining temporary directory
$file_des = $_SERVER['DOCUMENT_ROOT'] . '/storage/content/temp/';
// If not exists, create temp dir.
if(!file_exists($file_des)) mkdir($file_des);
// The first chunk have the original name of file uploaded
// so, if it exists in temp dir, upload the other pieces
// with anothers uniques names
if(file_exists($file_des . $filename)) {
$new_name = uniqid() . "." . pathinfo($filename, PATHINFO_EXTENSION);
move_uploaded_file($file_tmp, $file_des . $new_name);
// Now, append the chunk file to the first base file.
$handle = fopen($file_des . $new_name, 'rb');
$buff = fread($handle, filesize($file_des . $new_name));
fclose($handle);
$final = fopen($file_des . $filename, 'ab');
$write = fwrite($final, $buff);
fclose($final);
// Delete chunk
unlink($file_des . $new_name);
} else {
/* MAKE SURE WE DELETE THE CONTENT OF THE DESTINATION FOLDER FIRST,
OTHERWISE CHUNKS WILL BE APPENDED FOR EVER
IN CASE YOU ARE TRYING TO UPLOAD A FILE WITH THE EXACT SAME NAME.
CAREFUL: YOU MAY PREFER TO DELETE ONLY THE FILE
INSTEAD OF THE FOLDER'S CONTENT, IN THE CASE
YOUR FOLDER CONTAINS MORE THAN ONE FILE.
*/
$files_to_delete = glob($file_des."*"); // get all file names
foreach($files_to_delete as $file) // iterate files
{
if(is_file($file))
{
unlink($file); // delete file
}
}
// First chunk of file with original name.
move_uploaded_file($file_tmp, $file_des . $filename);
}