您的位置:首页 > Web前端

借助plupload插件实现前端JS分片上传并显示进度

2017-12-05 15:28 639 查看
在工作中发现了一个实用的JS上传图片插件,并且可以实现分片压缩上传和实时显示上传进度。

插件下载地址:https://github.com/moxiecode/plupload/tree/master/js

Plupload有以下功能和特点:

1、拥有多种上传方式:HTML5、flash、silverlight以及传统的<input type=”file” />。Plupload会自动侦测当前的环境,选择最合适的上传方式,并且会优先使用HTML5的方式。所以你完全不用去操心当前的浏览器支持哪些上传方式,Plupload会自动为你选择最合适的方式。

2、支持以拖拽的方式来选取要上传的文件

3、支持在前端压缩图片,即在图片文件还未上传之前就对它进行压缩

4、可以直接读取原生的文件数据,这样的好处就是例如可以在图片文件还未上传之前就能把它显示在页面上预览

5、支持把大文件切割成小片进行上传,因为有些浏览器对很大的文件比如几G的一些文件无法上传。

闲话不说,上代码;
部分实例代码:

html:

<h3 style="color: #FF0000">提示:先点击左侧图标选择上传文件后,再点击右侧"上传"按钮(仅可支持jpg/png/gif格式文件上传)</h3>
<div id="container" class="wu-example">
<div id="thelist" class="uploader-list"></div>
<div class="btns">
<div id="picker" class="webuploader-container">
<div class="webuploader-pick">选择文件</div>
<div id="pickfiles" style="position: absolute; top: 0px; left: 0px; width: 86px; height: 39px; overflow: hidden; bottom: auto; right: auto;">
<!--<input class="webuploader-element-invisible" name="file" multiple="multiple" accept="image/*" type="file">-->
<label style="opacity: 0; width: 100%; height: 100%; display: block; cursor: pointer; background: rgb(255, 255, 255) none repeat scroll 0% 0%;"></label>
</div>
<button id="uploadfiles" class="btn btn-default">开始上传</button>
</div>

</div>
</div>


JS:
var uploader = new plupload.Uploader({
runtimes : 'html5,flash,silverlight,html4',
browse_button : 'pickfiles', // you can pass an id...
//container: document.getElementById('container'), // ... or DOM Element itself
url : 'api/upload.php?img='+imgid,
flash_swf_url : '../js/Moxie.swf',
silverlight_xap_url : '../js/Moxie.xap',

filters : {
max_file_size : '10mb',
mime_types: [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
]
},

init: {
PostInit: function() {
document.getElementById('filelist').innerHTML = '';

document.getElementById('uploadfiles').onclick = function() {
uploader.start();
return false;
};

},

FilesAdded: function(up, files) {
plupload.each(files, function(file) {
document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
});
},

UploadProgress: function(up, file) {
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
},

FileUploaded: function(up, file, info) {
//console.log(info);
var data = eval("(" + info.response + ")");
$("#" + file.id).html("<img src='" + data.src + "'/><input type='hidden' name='idimg' value='"+ data.src +"'>");
$('#console').html("<font color='#f00'>"+data.msg+"</font>");
},

Error: function(up, err) {
document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message));
}
}
});

uploader.init();


php:
<?php
/**
* upload.php
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */

#!! IMPORTANT:
#!! this file is just an example, it doesn't incorporate any security checks and
#!! is not recommended to be used in production environment as it is. Be sure to
#!! revise it and customize to your needs.
set_time_limit(0);
include_once("../include/config.inc.php");
include_once("../include/zdefile.class.php");//文件处理

// Make sure file is not cached (as it happens for example on iOS devices)
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

/*
// Support CORS
header("Access-Control-Allow-Origin: *");
// other CORS headers if any...
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
exit; // finish preflight CORS requests here
}
*/

// 5 minutes execution time
@set_time_limit(5 * 60);

// Uncomment this one to fake upload time
// usleep(5000);

// Settings
//$targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
//$targetDir = 'uploads';
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 5 * 3600; // Temp file age in seconds

$file = $_FILES["file"];
$pid = $_SESSION['gz_xh_uid'];//用户ID
$imgid = $_GET['img'];//照片类型
$myfile = new zdeFile();

$oldpath = $file['tmp_name'];
$filetype = array("jpg", "png", "gif");//允许上传文件格式

$filename=strtolower(basename($file['name']));//取上传文件的小写文件名
$fileext=explode('.', $filename);//取后缀名
$arraynum = count($fileext) - 1;

if(!in_array($fileext[$arraynum], $filetype)){//检查文件类型
die("<script>alert('upload error!file type Error!');</script>");
}

$timepath = date('Y',time())."/".date('m',time())."/".date('d',time())."/";
$newpath = "../uploadfile/images/".$timepath;

$newname = time()."_$pid".".".$fileext[$arraynum];//新文件名
$newpath .= $newname;//新文件名
if($myfile->cp($oldpath,$newpath,true)){
//将照片存入数据库
$where = " and sysid=".$_SESSION['gz_xh_uid'];
if($imgid==1){
$arr = array(
'p_idcardimg1' => $newpath,
);
}elseif($imgid==2){
$arr = array(
'p_idcardimg2' => $newpath,
);
}else{
$arr = array(
'p_idcardimg3' => $newpath,
);
}

$res = update_record($GLOBALS['conn'],"game_player",$arr,array(),$where);
if($res){
die("{'msg' : '上传成功', 'src' : '$newpath'}");
}else{
die("upload error!");
}
}else{
die("upload error!");
}

/*// Create target dir
if (!file_exists($targetDir)) {
@mkdir($targetDir);
}

// Get a file name
if (isset($_REQUEST["name"])) {
$fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
$fileName = $_FILES["file"]["name"];
} else {
$fileName = uniqid("file_");
}

$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;

// Remove old temp files
if ($cleanupTargetDir) {
if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
}

while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

// If temp file is current file proceed to the next
if ($tmpfilePath == "{$filePath}.part") {
continue;
}

// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
@unlink($tmpfilePath);
}
}
closedir($dir);
}

// Open temp file
if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}

if (!empty($_FILES)) {
if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
}

// Read binary input stream and append it to temp file
if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
} else {
if (!$in = @fopen("php://input", "rb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
}
}

while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}

@fclose($out);
@fclose($in);

// Check if file has been uploaded
if (!$chunks || $chunk == $chunks - 1) {
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}*/

// Return Success JSON-RPC response
die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
9273
>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息