我正在使用角度ng-upload上传文件,这是我的javascript代码:
$scope.uploadFile = function(file) {
Upload.upload({
url: '/upload_image',
resumeChunkSize: '1MB',
data: {file: file}
}).then(function(response) {
console.log('success');
});
};
由于我是以块的形式上传文件,我希望后端的php能够读取并连接这些块,现在我该怎么做?我目前的PHP代码如下所示:
$filename = $_FILES['file']['name'];
$destination = '/someDestinationPath/' . $filename;
move_uploaded_file( $_FILES['file']['tmp_name'] , $destination );
但我很确定这不适用于块上传...
答案 0 :(得分:1)
好的,我已经想到了。当使用一些javascript库的块上传功能时,它们将参数传递给后端有关块信息的参数。在ng-file-upload的情况下,这些参数是_chunkNumber,_chunkSize和_totalSize。我对Plupload也是如此。做一些数学运算,你知道这个文件完成上传需要多少块。对于每个块上传,将有一个http post请求发送到后端PHP。足够的说话,代码在这里:
<强> PHP:强>
// uid is used to identify chunked partial files so we can assemble them back when all chunks are finished uploading
$uid = $_REQUEST['uid'];
$filename = $_REQUEST['filename'];
if (empty($_FILES['file']['name'])) {
return '';
}
if (isset($_POST['_chunkNumber'])) {
// the file is uploaded piece by piece, chunk mode
$current_chunk_number = $_REQUEST['_chunkNumber'];
$chunk_size = $_REQUEST['_chunkSize'];
$total_size = $_REQUEST['_totalSize'];
$upload_folder = base_path() . '/public/images/uploaded/';
$total_chunk_number = ceil($total_size / $chunk_size);
move_uploaded_file($_FILES['file']['tmp_name'], $upload_folder . $uid . '.part' . $current_chunk_number);
// the last chunk of file has been received
if ($current_chunk_number == ($total_chunk_number - 1)) {
// reassemble the partial pieces to a whole file
for ($i = 0; $i < $total_chunk_number; $i ++) {
$content = file_get_contents($upload_folder . $uid . '.part' . $i);
file_put_contents($upload_folder . $filename, $content, FILE_APPEND);
unlink($upload_folder . $uid . '.part' . $i);
}
}
} else {
// the file is uploaded as a whole, no chunk mode
move_uploaded_file($_FILES['file']['tmp_name'], $upload_folder . $filename);
}
Javascript(angularjs和ng-file-upload):
Upload.upload({
url: '/upload_image',
resumeChunkSize: '500KB',
data: {
filename: file.name
file: file
uid: toolbox.generateUniqueID()
}
}).then(function(response) {
console.log('success');
}), function(response) {
console.log('error');
});