对于很大的文件比如几百M的音频视频 软件上传,如果直接上传 服务器,经常处理不了。
可以利用layui,在客户端先把大文件切割成小文件 一个一个上传,然后服务器端,再组合成一个大文件。
服务端代码
public function bigUpload(Request $request)
{
$params = $request->param();
$status = 1;
$fname = sprintf('tmp/%s.%s', $params['fileName'],$params['fileExt']);
$data = file_get_contents($_FILES['file']['tmp_name']);
if ($_POST['page'] == 1) {
file_put_contents($fname, $data);
} else {
file_put_contents($fname, $data, FILE_APPEND);
}
$path = public_path()."tmp/{$params['fileName']}.{$params['fileExt']}";
if ($params['totalPage'] == $params['page']) {
$status = 2;
$url = $this->Oss($path);
$res = ['status' => $status, 'url' =>$url];
return json($res);
}
$res = ['status' => $status, 'url' => $path];
return json($res);
}
public function Oss($path)
{
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
$accessKeyId = “********";
$accessKeySecret = "********";
// Endpoint以杭州为例,其它Region请按实际情况填写。
$endpoint = "http://oss-cn-shanghai.aliyuncs.com";
// 设置存储空间名称。
$bucket = "bliuce";
// 设置文件名称。
$object = time() . ".jpg";
// <yourLocalFile>由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt。
$filePath = $path;
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$ossClient->uploadFile($bucket, $object, $filePath);
} catch (OssException $e) {
if ($e->getHTTPStatus() == 502 || $e->getErrorCode() == 400) {
return json(['code' => 300, 'msg' => '网络无连接,请稍后重试', 'data' => '']);
} else {
return json(['code' => 300, 'msg' => '未知错误', 'data' => '']);
}
}
$url = $this->getUrl($object);
return$url;
}
public function getUrl($obj)
{
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
$accessKeyId = "********";
$accessKeySecret = "********";
// Endpoint以杭州为例,其它Region请按实际情况填写。
$endpoint = "https://oss-cn-shanghai.aliyuncs.com";
$bucket = "bliuce";
$object = $obj;
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
// 生成一个带图片处理参数的签名的URL,有效期是3600秒,可以直接使用浏览器访问。
$timeout = 3600 * 5;
$options = array(
OssClient::OSS_PROCESS => "image/resize,m_lfit,h_100,w_100");
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
return $signedUrl;
}
前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>layui</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="./layui/css/layui.css" media="all">
<script src="./layui/layui.js" charset="utf-8"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
<style type="text/css">
.mask{position:fixed;width:100%;height:100%;top:0;left:0;background:#000;opacity:0.8;filter:alpha(Opacity=80);-moz-opacity:0.8;z-index:999;display:none;}
.loading{position:fixed;width:300px;left:50%;margin-left:-150px;top:200px;height:18px;border-radius:10px;background:#fff;z-index:9999;overflow:hidden;display:none;}
</style>
</head>
<body>
<div class="layui-main">
<form class="layui-form" method="post" action="">
<input type="hidden" name="form_submit" value="ok" />
<div class="layui-form-item">
<label class="layui-form-label">安装包:</label>
<input type="hidden" id="totalPage" value="0"/>
<input type="hidden" id="page" value="1"/>
<input type="hidden" id="status" value="0"/>
<div class="layui-input-block">
<button type="button" class="layui-btn" id="fileUpload"><i class="layui-icon"></i>上传文件</button>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">安装包名:</label>
<div class="layui-input-block">
<input type="text" name="name" id="name" value="" lay-verify="title" autocomplete="off" readonly="true" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">下载地址</label>
<div class="layui-input-block">
<input type="text" name="downUrl" id="downUrl" value="" lay-verify="downUrl" autocomplete="off" readonly="true" placeholder="" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit="" lay-filter="submit">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
</div>
<div class="mask"></div>
<div class="loading">
<div class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="uploadProgress">
<div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>
</div>
</div>
<!-- 注意:如果你直接复制所有代码到本地,上述js路径需要改成你本地的 -->
<script>
layui.use(['form', 'upload', 'element'], function () {
var form = layui.form;
var upload = layui.upload;
var element = layui.element;
var $ = layui.$;
upload.render({
elem: '#fileUpload',
url: 'upload.php', //处理上传文件接口
accept: 'file',
auto: false,
acceptMime: '.exe,.zip,.rar,.gz',//允许上传的文件类型
choose: function (obj) {
element.progress('uploadProgress', '0%');
$('.mask').show();
$('.loading').show();
var data = this.data;
var files = obj.pushFile();
var LENGTH = 500 * 1024; //每片文件大小
obj.preview(function (index, file, result) {
var totalSize = file.size;
var totalPage = Math.ceil(totalSize / LENGTH);
$('#totalPage').val(totalPage);
$('#page').val('1');
$('#status').val('1');
var fileName = file.name;
$('#name').val(fileName);
var fileExt = fileName.substr(fileName.lastIndexOf('.') + 1);
fileName = fileName.substr(0, fileName.lastIndexOf('.'));
var progressTimer = setInterval(function () {
var totalPage = parseInt($('#totalPage').val());
var page = parseInt($('#page').val());
var status = $('#status').val();
if (parseInt(totalPage) == parseInt(page) && (parseInt(status) == 2 || parseInt(status) == -1)) {
clearInterval(progressTimer);
} else {
if (status == 1) {
$('#status').val('0');
data.fileName = fileName;
data.page = page;
data.totalPage = totalPage;
data.fileExt = fileExt;
obj.upload(index, file.slice((page - 1) * LENGTH, page * LENGTH));
}
}
}, 100);
});
},
done: function (res) {
if (res.status == 1) { //分片上传
var page = parseInt($('#page').val());
var totalPage = parseInt($('#totalPage').val());
element.progress('uploadProgress', Math.ceil(page * 100 / totalPage) + '%');
page = page + 1;
console.log(page);
$('#page').val(page);
$('#status').val('1');
} else if (res.status == 2) { //上传完成
element.progress('uploadProgress', '100%');
$('#status').val('2');
$('#downUrl').val(res.url);
layer.msg('上传成功', {time: 1000, anim: 0}, function () {
$('.mask').hide();
$('.loading').hide();
});
} else { //上传错误
$('#status').val('-1');
element.progress('uploadProgress', '0%');
console.log(!typeof (res.downUrl) == "undefined");
if (typeof (res.downUrl) == "undefined") {
} else {
$('#downUrl').val(res.downUrl);
}
layer.msg("上传失败,请重试", {time: 3000, anim: 0}, function () {
$('.mask').hide();
$('.loading').hide();
});
}
},
error: function(){
$('.mask').hide();
$('.loading').hide();
}
});
});
</script>
</body>
</html>
|