plupload.js+php批量上传文件到阿里云oss
作者:互联网
最近写了一个批量上传文件的功能,前端用的plupload.js,后台用的php。
页面引用
<link rel="stylesheet" href="./js/jquery.plupload.queue/css/jquery.plupload.css" type="text/css" media="screen" />
<script type="text/javascript" src="./js/plupload.full.min.js"></script>
html:
<div class="form-group row mb-3">
<label class="col-sm-2 control-label">文件区域</label>
<div class="col-md-6 col-sm-10 font-14">
<div>
<div id="add_file" class="div-boder" style="width:34px;height: 34px">
<a class="video_upload_btn" id="video_upload_btn" style="height: 30px;width: 30px;justify-content: center;align-items: center;display: flex">
<span>+</span></a>
</div>
<div id="video_upload_area" class="div-boder margin-top-10">
<div class="video_textarea_upload" id="video_textarea_upload2">
<div class="video_upload_words" style="min-height: 80px">
</div>
</div>
</div>
</div>
<div class="video_notice">文件可拖动到虚线框内,最多可选择10个文件</div>
<div class="upload_video_area" id="upload_video_area">
<a id="upload_video" class="btn btn-secondary disabled" href="javascript:void(0);">开始上传</a>
</div>
</div>
</div>
<div class="form-group row mb-3 shipin" >
<label class="col-sm-2 control-label layui-form-label"></label>
<div class="col-md-6 col-sm-10 layui-input-block">
<input type="text" id="dz" name="address" class="form-control layui-input" />
</div>
</div>
<div class="form-group row mb-3">
<label class="col-sm-2 control-label"></label>
<div class=" col-sm-10 dropzone-previews mt-3" id="file-list">
<div class="card mt-1 mb-0 shadow-none border video_name_box" id="o_1epqie8n3vr8htt1u351bi71acad">
<div>
<div class="div-flex align-items-center">
<div class="col-auto">
<span class="text-muted font-weight-bold">u=1333028813,1376054428&fm=26&gp=0.jpg</span>
</div>
<div class="col pl-0">
<span class="text-muted font-weight-bold">19.85KB</span>
</div>
<div class="col-auto">
<div class="div-bar">
<div class="div-bar2" style="width:65%"></div>
</div>
</div>
<div class="col-auto">
<a href="javascript:void(0)" class="btn btn-link btn-lg text-muted" data-id="o_1epqie8n3vr8htt1u351bi71acad" onclick="remove_file(this)">
<i class="mdi mdi-close-circle font-18"></i>
</a>
</div>
</div>
</div>
</div>
<div class="card mt-1 mb-0 shadow-none border video_name_box" id="o_1epqie8n3136m110t1622qu8dvbe">
<div>
<div class="div-flex align-items-center">
<div class="col-auto">
<span class="text-muted font-weight-bold">城南花开.mp3</span>
</div>
<div class="col pl-0">
<span class="text-muted font-weight-bold">1.06MB</span>
</div>
<div class="col-auto">
<div class="div-bar">
<div class="div-bar2" style="width:35%"></div>
</div>
</div>
<div class="col-auto">
<a href="javascript:void(0)" class="btn btn-link btn-lg text-muted" data-id="o_1epqie8n3136m110t1622qu8dvbe" onclick="remove_file(this)">
<i class="mdi mdi-close-circle font-18"></i>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
js:
<script type="text/javascript">
let uploader_video = new plupload.Uploader({
runtimes: 'gears,html5,html4,silverlight,flash',
browse_button: ['video_upload_btn'], // 上传按钮
url: "{:url('media/upVideos')}", //远程上传地址
flash_swf_url: '__STATIC__/plupload-master/js/Moxie.swf', //flash文件地址
silverlight_xap_url: '__STATIC__/plupload-master/js/Moxie.xap', //silverlight文件地址
filters: {
max_file_size: '1gb', //最大上传文件大小(格式100b, 10kb, 10mb, 1gb)
mime_types: [//允许文件上传类型mp4|mov|m4v|3gp|avi|m3u8|webm mp4,flv,3gp,mov,avi,rmvb,mkv,wmv
{title: "files", extensions: "gif,jpg,jpeg,png,GIF,JPG,PNG,mp3,wma,wav,mp4,m4v,3gp,mov,avi,m3u8,webm"}
]
},
//chunk_size:'512kb', //切片文件大小
file_data_name:'files',
multi_selection: true, //true:ctrl多文件上传, false 单文件上传
drop_element:'video_upload_area',
init: {
//文件上传前
FilesAdded: function(up, files) {
let file_length=$(".video_name_box").length;
for (let i=0;i<files.length;i++) {
let size=formatFileSize(files[i].size);
let k= '<div class="card mt-1 mb-0 shadow-none border video_name_box" id="'+files[i].id+'">' +
'<div>'+
'<div class="div-flex align-items-center">'+
'<div class="col-auto">'+
'<span class="text-muted font-weight-bold">'+files[i].name+
'</span>'+
'</div>'+
'<div class="col pl-0">'+
'<span class="text-muted font-weight-bold">'+size+
'</span>'+
'</div>'+
'<div class="col-auto bar" style="display: none">'+
'<div class="div-bar">'+
'<div class="div-bar2" style="width:65%"></div>'+
'</div>'+
'</div>'+
'<div class="col-auto">'+
'<a href="javascript:void(0)" class="btn btn-link btn-lg text-muted" data-id="'+files[i].id+'" onclick="remove_file(this)">'+
'<i class="mdi mdi-close-circle font-18" ></i></a>'+
'</div>' +
'</div></div>' +
'</div>';
if (file_length ==10){
alert("最多添加10个文件");
} else {
$("#file-list").append(k);
}
}
$("#upload_video").removeClass("disabled");
$("#upload_video").click(function() {
uploader_video.start();
//调用实例对象的start()方法开始上传文件,当然你也可以在其他地方调用该方法
});
},
//上传中,显示进度条
UploadProgress: function(up, file) {
var percent = file.percent;
var file_id = file.id;
$("#" + file_id).find('.bar').css({"display":'block'});
$("#" + file_id).find('.div-bar2').css({"width": percent + "%"});
},
//文件上传成功的时候触发
FileUploaded: function(up, file, info) {
let data = JSON.parse(info.response);
let k=$("#dz");
let dz=k.val();
if (dz==null || dz==''){
k.val(data.data);
}else {
k.val(dz+","+data.data);
}
//上传完成,删除文件
var file_id = file.id;
$('#'+file_id).remove();
},
//上传出错的时候触发
Error: function(up, err) {
alert(err.message);
}
}
});
//实例化
uploader_video.init();
//将文件大小换算
function formatFileSize(fileSize) {
if (fileSize < 1024) {
return fileSize + 'B';
} else if (fileSize < (1024*1024)) {
var temp = fileSize / 1024;
temp = temp.toFixed(2);
return temp + 'KB';
} else if (fileSize < (1024*1024*1024)) {
var temp = fileSize / (1024*1024);
temp = temp.toFixed(2);
return temp + 'MB';
} else {
var temp = fileSize / (1024*1024*1024);
temp = temp.toFixed(2);
return temp + 'GB';
}
}
//删除文件
function remove_file(obj){
let file_id=obj.getAttribute("data-id");
let obj_file = uploader_video.getFile(file_id);
uploader_video.removeFile(obj_file);
$('#'+file_id).remove();
}
</script>
php:
public function upVideos(){
$param=$_POST;
header("Content-type: text/html; charset=utf-8");
//获取文件后缀名
$strFileExtension = strtolower(get_file_extension($param['name']));
$strDate = date('Ymd');
$app = 'manage';
$fileSaveName = (empty($app) ? '' : $app . '/') . $strDate . '/' . md5(uniqid()) . "." . $strFileExtension;
$filePath = $_FILES['files']['tmp_name'];
$result=$this->multipartUpload($filePath,$fileSaveName);
if(!empty($result['info'])){
$path=$result['info']['url']
return json(array("code" => 1, "msg" =>'上传成功', "data" => $path));
}else{
return json_encode(array("code" => 0,"msg"=>"上传有误,请检查服务器配置!"));
}
// 阿里云分片上传
private function multipartUpload($uploadFile,$object){
//第一步 初始化分片上传
$option=['accessKeyId'=>'','accessKeySecret'=>'','endpoint'=>'','bucket'=>''];
$ossClient = new OssClient($option['accessKeyId'], $option['accessKeySecret'], $option['endpoint']);
try{
//返回uploadId。uploadId是分片上传事件的唯一标识,您可以根据uploadId发起相关的操作,如取消分片上传、查询分片上传等。
$uploadId = $ossClient->initiateMultipartUpload($option['bucket'], $object);
} catch(OssException $e) {
$result = $e->getMessage();
}
//第二步 分片上传及设置
$partSize = 2 * 1024 * 1024;//分片文件2m
$uploadFileSize = filesize($uploadFile);
$pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize);
$responseUploadPart = array();
$uploadPosition = 0;
$isCheckMd5 = true;
foreach ($pieces as $i => $piece) {
$fromPos = $uploadPosition + (integer)$piece[$ossClient::OSS_SEEK_TO];
$toPos = (integer)$piece[$ossClient::OSS_LENGTH] + $fromPos - 1;
$upOptions = array(
// 上传文件。
$ossClient::OSS_FILE_UPLOAD => $uploadFile,
// 设置分片号。
$ossClient::OSS_PART_NUM => ($i + 1),
// 指定分片上传起始位置。
$ossClient::OSS_SEEK_TO => $fromPos,
// 指定文件长度。
$ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
// 是否开启MD5校验,true为开启。
$ossClient::OSS_CHECK_MD5 => $isCheckMd5,
);
// 开启MD5校验。
if ($isCheckMd5) {
$contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos);
$upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5;
}
try {
// 上传分片。
$responseUploadPart[] = $ossClient->uploadPart($option['bucket'], $object, $uploadId, $upOptions);
} catch(OssException $e) {
$result = $e->getMessage();
}
}
// $uploadParts是由每个分片的ETag和分片号(PartNumber)组成的数组。
$uploadParts = array();
foreach ($responseUploadPart as $i => $eTag) {
$uploadParts[] = array(
'PartNumber' => ($i + 1),
'ETag' => $eTag,
);
}
//第三步 合并分片
try {
// 执行completeMultipartUpload操作时,需要提供所有有效的$uploadParts。OSS收到提交的$uploadParts后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。
$result=$ossClient->completeMultipartUpload($option['bucket'], $object, $uploadId, $uploadParts);
} catch(OssException $e) {
$result = $e->getMessage();
}
return $result;
}
效果图如下:
标签:1024,temp,oss,ossClient,js,file,分片,php,上传 来源: https://www.cnblogs.com/somebody-hxy/p/14156202.html