详解利用plupload突破HTTP上传限制

plupload 是一款国外的上传开源组件,官方使用PHP作为服务器语言。这篇文章主要介绍plupload的在上传大文件方面的应用。

plupload支持技术:

1:Flash
2:Gears
3:HTML 5
4:Silverlight
5:BrowserPlus
6:HTML 4

plupload主要功能:

1:突破HTTP上传限制,可上传大文件,官方论坛中有讨论上传2G文件的应用。
2:多文件队列上传
3:图片自动生成缩略图
4:上传后自动生成唯一文件名
5:自定制UI

由于plupload 确实是一个功能比较强大的组件所以无法一一介绍所有功能特色,这里主要就网站开发中plupload上传大文件的问题进行思路与代码的解析 。

大文件上传思路:plupload的上传思路是将一个较大的文件分成多个小块进行上传从而达到突破服务器上传限制的目的。这估计也是唯一的方法了,但本人测试过程中根据虚拟主机差异分块上传时对于可能会出现块数太多中断的原因,但这肯定是服务器的配置问题,更换服务器后该问题解决,也就是说大部分服务器均没有问题的。


下载最新版本后按照官方DEMO进行安装。

JS参数配置说明:

<script type="text/javascript"> 

$(function() {
$("#uploader").pluploadQueue({

runtimes : 'gears,flash,silverlight,browserplus,html5', // 这里是说用什么技术引擎,由于国内浏览器问题这里一般使用flash即可。其他的删除掉。
url : 'upload.php', // 服务端上传路径
max_file_size : '10mb', // 文件上传最大限制。
chunk_size : '1mb', // 上传分块每块的大小,这个值小于服务器最大上传限制的值即可。(文件总大小/chunk_size = 分块数)。
unique_names : true, // 上传的文件名是否唯一
resize : {width : 320, height : 240, quality : 90}, // 是否生成缩略图(仅对图片文件有效)。

filters : [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
], // 这个数组是选择器,就是上传文件时限制的上传文件类型

flash_swf_url : '/plupload/js/plupload.flash.swf', // plupload.flash.swf 的所在路径
silverlight_xap_url : '/plupload/js/plupload.silverlight.xap' // silverlight所在路径

});

// 这一块主要是防止在上传未结束前表带提交,具体大家可酌情修改编写
$('form').submit(function(e) {
var uploader = $('#uploader').pluploadQueue(); // 取得上传队列
if (uploader.files.length > 0) { // 就是说如果上传队列中还有文件
uploader.bind('StateChanged', function() {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
} else {
alert('You must queue at least one file.');
}
return false;
});

});
</script>

 

由于参数过多大家可以到官方网站查看API参数说明。

服务端代码说明:
官方自带了PHP版本的DEMO文件。大家一定要参考这个DEMO进行编写或者直接使用。在此我简单的做一下官方upload.php的注释说明。

<?php

// HTTP headers for no cache etc 头部没有缓存
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");

//上传路径
$targetDir = 'uploads/';

// 脚本执行时间
@set_time_limit(5 * 60);
// 延迟
// usleep(5000);

// 接收 pluploa的参数

$chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
$chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';

// 文件名整理
$fileName = preg_replace('/[^\w\._]+/', '', $fileName);

// 这里主要是如果JS参数设置了唯一文件名,则进行唯一文件名的处理,chunks<2 的意思是只有在不分块上传的情况下才会进行唯一文件名。否则将和分块上传的原理冲突,第1块以后的文件流将无法写入正确的文件中。
if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
$ext = strrpos($fileName, '.');
$fileName_a = substr($fileName, 0, $ext);
$fileName_b = substr($fileName, $ext);

$count = 1;
while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
$count++;

$fileName = $fileName_a . '_' . $count . $fileName_b;
}

/*创建文件目录*/
if (!file_exists($targetDir))
@mkdir($targetDir);

if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
while (($file = readdir($dir)) !== false) {
$filePath = $targetDir . DIRECTORY_SEPARATOR . $file;

// Remove temp files if they are older than the max age
if (preg_match('/\\.tmp$/', $file) && (filemtime($filePath) < time() - $maxFileAge))
@unlink($filePath);
}

closedir($dir);
} else
die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
*/

// 上传写文件步骤,这一部分以下的代码可直接引用
if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
$contentType = $_SERVER["HTTP_CONTENT_TYPE"];

if (isset($_SERVER["CONTENT_TYPE"]))
$contentType = $_SERVER["CONTENT_TYPE"];

// Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
if (strpos($contentType, "multipart") !== false) {
if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
// Open temp file
$out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
if ($out) {
// Read binary input stream and append it to temp file
$in = fopen($_FILES['file']['tmp_name'], "rb");

if ($in) {
while ($buff = fread($in, 4096))
fwrite($out, $buff);
} else
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
fclose($in);
fclose($out);
@unlink($_FILES['file']['tmp_name']);
} else
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
} else
die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
} else {
// Open temp file
$out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
if ($out) {
// Read binary input stream and append it to temp file
$in = fopen("php://input", "rb");

if ($in) {
while ($buff = fread($in, 4096))
fwrite($out, $buff);
} else
die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');

fclose($in);
fclose($out);
} else
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}

// Return JSON-RPC response
die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');

?>

 

参考资料:

www.mwinds.net

www.plupload.com 

由于该组件确实很强大,但是中文资料非常的少,所以发表这篇文章希望对大家有所帮助。以后将会陆续介绍plupload的其他方面应用比如自定制上传问题跟IE兼容问题。


 

转载于:https://www.cnblogs.com/mwinds/archive/2011/12/03/2274704.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值