首页 > 编程语言 >php结合web uploader插件实现分片上传文件

php结合web uploader插件实现分片上传文件

时间:2023-10-27 10:11:37浏览次数:34  
标签:web 插件 uploader index die filePath REQUEST file id

这篇文章主要为大家详细介绍了php结合web uploader插件实现分片上传文件, 采用大文件分片并发上传,极大的提高了文件上传效率,感兴趣的小伙伴们可以参考一下  

最近研究了下大文件上传的方法,找到了webuploader js 插件进行大文件上传,大家也可以参考这篇文章进行学习:《Web Uploader文件上传插件使用详解

使用

 使用webuploader分成简单直选要引入

<!--引入CSS-->
<link rel="stylesheet" type="text/css" href="webuploader文件夹/webuploader.css">

<!--引入JS-->
<script type="text/javascript" src="webuploader文件夹/webuploader.js"></script>

 

HTML部分

<div id="uploader" class="wu-example">
<!--用来存放文件信息-->
<div id="thelist" class="uploader-list"></div>
<div class="btns">
<div id="picker">选择文件</div>
<button id="ctlBtn" class="btn btn-default">开始上传 </button>
</div>
</div>

初始化Web Uploader

jQuery(function() {
$list = $('#thelist'),
$btn = $('#ctlBtn'),
state = 'pending',
uploader;

uploader = WebUploader.create({
// 不压缩image
resize: false,
// swf文件路径
swf: 'uploader.swf',
// 文件接收服务端。
server: upload.php,
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#picker',
chunked: true,
chunkSize:2*1024*1024,
auto: true,
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
}
});

upload.php处理

以下是根据别人的例子自己拿来改的php 后台代码

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");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
exit; // finish preflight CORS requests here
}
if ( !empty($_REQUEST[ 'debug' ]) ) {
$random = rand(0, intval($_REQUEST[ 'debug' ]) );
if ( $random === 0 ) {
header("HTTP/1.0 500 Internal Server Error");
exit;
}
}

// header("HTTP/1.0 500 Internal Server Error");
// exit;
// 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'.DIRECTORY_SEPARATOR.'file_material_tmp';
$uploadDir = 'uploads'.DIRECTORY_SEPARATOR.'file_material';
$cleanupTargetDir = true; // Remove old files
$maxFileAge = 5 * 3600; // Temp file age in seconds
// Create target dir
if (!file_exists($targetDir)) {
@mkdir($targetDir);
}
// Create target dir
if (!file_exists($uploadDir)) {
@mkdir($uploadDir);
}
// Get a file name
if (isset($_REQUEST["name"])) {
$fileName = $_REQUEST["name"];
} elseif (!empty($_FILES)) {
$fileName = $_FILES["file"]["name"];
} else {
$fileName = uniqid("file_");
}
$oldName = $fileName;
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
// $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
// Chunking might be enabled
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
// 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}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
continue;
}
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
@unlink($tmpfilePath);
}
}
closedir($dir);
}

// Open temp file
if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "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);
rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
$index = 0;
$done = true;
for( $index = 0; $index < $chunks; $index++ ) {
if ( !file_exists("{$filePath}_{$index}.part") ) {
$done = false;
break;
}
}

 

if ( $done ) {
$pathInfo = pathinfo($fileName);
$hashStr = substr(md5($pathInfo['basename']),8,16);
$hashName = time() . $hashStr . '.' .$pathInfo['extension'];
$uploadPath = $uploadDir . DIRECTORY_SEPARATOR .$hashName;

if (!$out = @fopen($uploadPath, "wb")) {
die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
}
if ( flock($out, LOCK_EX) ) {
for( $index = 0; $index < $chunks; $index++ ) {
if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
break;
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
@fclose($in);
@unlink("{$filePath}_{$index}.part");
}
flock($out, LOCK_UN);
}
@fclose($out);
$response = [
'success'=>true,
'oldName'=>$oldName,
'filePaht'=>$uploadPath,
'fileSize'=>$data['size'],
'fileSuffixes'=>$pathInfo['extension'],
'file_id'=>$data['id'],
];

die(json_encode($response));
}

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

以上就是本文的全部内容,希望对大家的学习有所帮助

 

参考文章:http://blog.ncmem.com/wordpress/2023/10/27/php%e7%bb%93%e5%90%88web-uploader%e6%8f%92%e4%bb%b6%e5%ae%9e%e7%8e%b0%e5%88%86%e7%89%87%e4%b8%8a%e4%bc%a0%e6%96%87%e4%bb%b6/

欢迎入群一起讨论

 

 

标签:web,插件,uploader,index,die,filePath,REQUEST,file,id
From: https://www.cnblogs.com/songsu/p/17791135.html

相关文章

  • 30-Vue脚手架-plugin插件
    plugin插件功能:用于增强Vue本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。 src/plugins.js(定义插件)//定义插件(默认暴露)exportdefault{install(Vue){console.log("@@@install")console.log(......
  • web基础漏洞-额外
    1、介绍这里阐述除了web基础漏洞之外的漏洞大全,简要列举,以供快速查询。分为几大类:服务器容器、cms、前端api、后端api、操作系统和端口服务2、服务器容器tomcat后台弱口令war包上传tomcatput漏洞tomcatajp漏洞nignx目录穿越漏洞apache解析顺序漏洞apache.htaccess配置......
  • playwright -启动本地chrome浏览器-启动扩展程序-插件
    fromplaywright.sync_apiimportsync_playwrightimportosclassTool:def__init__(self,user_data_dir,executable_path):playwright=sync_playwright().start()#启动扩展程序-开启影刀插件path_to_extension=r"D:\data\google\Ch......
  • Buu web easysql and Havefun
    1.easysql:(sql注入)解题思路:1、手工sql注入判断注入类型。2、构造pyload输入1’判断注入类型页面报错,说明为字符型,在构造pyload时候,需要主要闭合'。pyload:1'or1=1#(#的意思是把后面的注释掉,在这里是注释掉后面',保证语句正常执行)用or是因为1=1为真,那么无论前面的条......
  • 超好用的IDEA插件推荐!自带API调试功能
    大家好,今天给大家推荐一款超好用的IDEA插件,由API调试工具Apipost推出!支持在插件中获取token、支持代码完成后在插件中进行API调试,同时也保留了1.0版本部分功能如上传选择目录功能等。V1版本还会继续保留开源,方便各位进行自创魔改。V2版本目前已上架至IDEA插件商店,大家可以自行下......
  • javaweb--mysql数据模型
    关系型数据库由多张可以相互连接的二维表组成的数据库frm表文件myd数据文件注释/**/多行注释--和#单行注释四类语法DDL数据定义语言DML数据操作语言DQL数据查询语言DCL数据控制语言原始数据库information_schema存储数据库的基本信息,存储的库名表名列名等mysql存......
  • 超好用的IDEA插件推荐!自带API调试功能
    大家好,今天给大家推荐一款超好用的IDEA插件,由API调试工具Apipost推出!支持在插件中获取token、支持代码完成后在插件中进行API调试,同时也保留了1.0版本部分功能如上传选择目录功能等。V1版本还会继续保留开源,方便各位进行自创魔改。V2版本目前已上架至IDEA插件商店,大家可以自行......
  • 干货!分享Nginx搭建web测试报告服务器的落地方案
    Nginx搭建web测试报告服务器的实现思路有这样一个需求:把自动化测试过程中生成的html测试报告能够通过浏览器直接访问查看!实现思路很简单,就是部署一个web服务器,然后把测试报告部署到web服务器的指定目录即可,然后通过http://ip:port/path/报告名称.html的形式进行访问。我们通过ngin......
  • TestNG+Webdriver 页面自动化详解
    最近学习了一下TestNG+Webdriver的页面自动化,虽然中间遇到了很多问题,也走了不少弯路,不过最终还是运行起来了。下面就详细讲解一下,如何去配置环境及编写测试用例!环境配置1,eclipse+jkd的安装这是基本的开发环境,具体的配置在此就不累述了,网上有很多相关文档,请自行查阅。2,TestNG......
  • kubectl 插件
    https://kubernetes.io/zh-cn/docs/reference/kubectl/kubectl支持使用任何编程语言定义插件,插件位置必须要在$PATH路径中,必须要有可执行权限,命令必须以kubectl为前缀示例:编写脚本并放在PATH中root@master01:~#cat/usr/local/bin/kubectl-hello#!/bin/bashechohell......