在ThinkPHP框架中,可以使用第三方插件JQuery-File-Upload来实现分片上传。
具体步骤如下:
在composer.json文件中添加依赖:"blueimp/jquery-file-upload": "^9.28.0"
使用composer install 命令安装依赖
在控制器中处理上传请求
public function upload()
{
$uploadHandler = new \Blueimp\FileUpload\UploadHandler();
header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Content-Disposition: inline; filename="files.json"');
header('X-Content-Type-Options: nosniff');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition');
switch ($_SERVER['REQUEST_METHOD']) {
case 'OPTIONS':
break;
case 'HEAD':
case 'GET':
$uploadHandler->get();
break;
case 'POST':
if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE') {
$uploadHandler->delete();
} else {
$uploadHandler->post();
}
break;
case 'DELETE':
$uploadHandler->delete();
break;
default:
header('HTTP/1.1 405 Method Not Allowed');
}
}
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="//blueimp.github.io/Gallery/css/blueimp-gallery.min.css">
<link rel="stylesheet" href="/path/to/jquery.fileupload.css">
<link rel="stylesheet" href="/path/to/jquery.fileupload-ui.css">
</head>
<body>
<input id="fileupload" type="file" name="files[]" multiple>
<div id="progress"></div>
<div id="files" class="files"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<script src="//blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js"></script>
<script src="/path/to/jquery.iframe-transport.js"></script>
<script src="/path/to/jquery.fileupload.js"></script>
<script src="/path/to/jquery.fileupload-process.js"></script>
<script src="/path/to/jquery.fileupload-validate.js"></script>
<script src="/path/to/jquery.fileupload-ui.js"></script>
<script>
$(function () {
$('#fileupload').fileupload({
url: '/upload',
dataType: 'json',
autoUpload: true,
maxChunkSize: 10000000, //设置分片大小为10MB
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
</body>
</html>
以上就是使用ThinkPHP框架实现分片上传的步骤。需要注意的是,在上传过程中需要处理上传进度和分片大小等问题。