思路:将js传过来的数据存储为多个临时文件,然后通过代码合并为一个完整文件。
直接上代码:
"临时文件错误",
"ERROR_TMP_FILE_NOT_FOUND" => "找不到临时文件",
"ERROR_SIZE_EXCEED" => "文件大小超出网站限制",
"ERROR_TYPE_NOT_ALLOWED" => "文件类型不允许",
"ERROR_CREATE_DIR" => "目录创建失败",
"ERROR_DIR_NOT_WRITEABLE" => "目录没有写权限",
"ERROR_CREATE_TMP_DIR" => "临时目录创建失败",
"ERROR_TMP_DIR_NOT_WRITEABLE" => "临时目录没有写权限",
"ERROR_TMP_DIR_OPEN" => "打开临时目录失败",
"ERROR_CHUNK_TMP_FILE" => "打开临时分片文件失败",
"ERROR_FILE_MOVE" => "文件保存时出错",
"ERROR_FILE_NOT_FOUND" => "找不到上传文件",
"ERROR_WRITE_CONTENT" => "写入文件内容错误",
"ERROR_UNKNOWN" => "未知错误",
"ERROR_DEAD_LINK" => "链接不可用",
"ERROR_HTTP_LINK" => "链接不是http链接",
"ERROR_HTTP_CONTENTTYPE" => "链接contentType不正确",
"INVALID_URL" => "非法 URL",
"INVALID_IP" => "非法 IP"
);
static $imageMimeList = [
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'wbmp' => 'image/wbmp',
];
/**
* 构造函数
* @param string $fileField 表单名称
* @param array $config 配置项
* @param bool $base64 是否解析base64编码,可省略。若开启,则$fileField代表的是base64编码的字符串表单名
*/
public function __construct($fileField, $config, $type = "upload")
{
$this->fileField = $fileField;
$this->config = $config;
$this->type = $type;
if ($type == "remote") {
$this->saveRemote(); // 保存远程文件
} else if ($type == "base64") {
$this->upBase64(); // 保存base64文件
} else {
$this->upFile(); // 上传文件
}
$this->stateMap['ERROR_TYPE_NOT_ALLOWED'] = iconv('unicode', 'utf-8', $this->stateMap['ERROR_TYPE_NOT_ALLOWED']);
}
/**
* 上传文件的主处理方法
* @return mixed
*/
private function upFile()
{
// 文件
$file = $this->file = $_FILES[$this->fileField];
// 上传文件为空
if (!$file) {
$this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
return;
}
// 上传时发生错误
if ($this->file['error']) {
$this->stateInfo = $this->getStateInfo($file['error']);
return;
} else if (!file_exists($file['tmp_name'])) {
$this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
return;
} else if (!is_uploaded_file($file['tmp_name'])) {
$this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
return;
}
$this->oriName = $file['name']; // 原始的文件名
$this->fileSize = $file['size']; // 文件大小
$this->fileType = $this->getFileExt(); // 扩展
$this->fullName = $this->getFullName(); // 新的文件名(包含相对路径)
$this->filePath = $this->getFilePath(); // 文件路径(全路径)
$this->fileName = $this->getFileName(); // 文件名
$dirname = dirname($this->filePath); // 文件夹名
//检查文件大小是否超出限制
if (!$this->checkSize()) {
$this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
return;
}
//检查是否不允许的文件格式
if (!$this->checkType()) {
$this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
return;
}
//创建目录失败
if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
$this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
return;
} else if (!is_writeable($dirname)) {
$this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
return;
}
// 判断是否为分片上传
if (isset($_REQUEST["chunk"]) && isset($_REQUEST["chunks"])) { // 如果是分片上传
// 临时文件夹
$tmpDir = $this->getFileTmpPath();
$cleanUpTmpDir = true; // 是否清除临时文件
$maxFileAge = 3600; // 上传过程中发现有超过该时间没被清除的临时文件,顺手清除一下
//创建临时目录失败
if (!file_exists($tmpDir) && !mkdir($tmpDir, 0777, true)) {
$this->stateInfo = $this->getStateInfo("ERROR_CREATE_TMP_DIR");
return;
} else if (!is_writeable($tmpDir)) {
$this->stateInfo = $this->getStateInfo("ERROR_TMP_DIR_NOT_WRITEABLE");
return;
}
// 临时文件路径
$tmpFileName = $this->oriName;
if (substr($tmpFileName, 0, 1) != '/') {
$tmpFileName = '/' . $tmpFileName;
}
$tmpFilePath = $tmpDir . $tmpFileName;
// 第几片
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
// 共分了多少片 类型int
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
// 判断是否清除临时文件夹文件
if ($cleanUpTmpDir) {
if (!is_dir($tmpDir) || !$dir = opendir($tmpDir)) {
$this->stateInfo = $this->getStateInfo("ERROR_TMP_DIR_OPEN");
return;
}
// 读取临时文件夹内容
while (($f = readdir($dir)) !== false) {
$tmpfilepath = $tmpDir . '/' . $f;
// If temp file is current file proceed to the next
if ($tmpfilepath == "{$tmpFilePath}_{$chunk}.part" || $tmpfilepath == "{$tmpFilePath}_{$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)$/', $f) && (@filemtime($tmpfilepath) < time() - $maxFileAge)) {
@unlink($tmpfilepath);
}
}
// 关闭文件夹
closedir($dir);
}
// 打开临时文件
if (!$out = @fopen("{$tmpFilePath}_{$chunk}.parttmp", "wb")) {
$this->stateInfo = $this->getStateInfo("ERROR_CHUNK_TMP_FILE"); // 打开临时分片文件错误
return;
}
// Read binary input stream and append it to temp file
if (!$in = @fopen($file["tmp_name"], "rb")) {
$this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE"); // 临时文件错误
return;
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
@fclose($out);
@fclose($in);
rename("{$tmpFilePath}_{$chunk}.parttmp", "{$tmpFilePath}_{$chunk}.part");
$done = true;
for ($index = 0; $index < $chunks; $index++) {
if (!file_exists("{$tmpFilePath}_{$index}.part")) {
$done = false;
break;
}
}
// 所有分片上传完成之后
if ($done) {
if (!$out = @fopen($this->filePath, "wb")) {
//$errMsg = 'Failed to open output stream';
$this->stateInfo = $this->getStateInfo("ERROR_OPEN_OUTPUT_STREAM"); // 临时文件错误
return;
}
if (flock($out, LOCK_EX)) {
for ($index = 0; $index < $chunks; $index++) {
if (!$in = @fopen("{$tmpFilePath}_{$index}.part", "rb")) {
break;
}
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
@fclose($in);
@unlink("{$tmpFilePath}_{$index}.part");
}
flock($out, LOCK_UN);
}
@fclose($out);
// 合并完成
$this->stateInfo = $this->stateMap[0];
return;
}
// 每一个分片上传完成时
$this->stateInfo = ["state" => $this->stateMap[1], "msg" => '第' . ($chunk + 1) . '片上传成功/共' . $chunks . '片'];
} else {// 如果不是分片上传,直接移动文件到新文件路径即可
//移动文件
if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
$this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
} else { //移动成功
$this->stateInfo = $this->stateMap[0];
}
}
}
/**
* 处理base64编码的图片上传
* @return mixed
*/
private function upBase64()
{
$base64Data = $_POST[$this->fileField];
$img = base64_decode($base64Data);
$this->oriName = $this->config['oriName'];
$this->fileSize = strlen($img);
$this->fileType = $this->getFileExt();
$this->fullName = $this->getFullName();
$this->filePath = $this->getFilePath();
$this->fileName = $this->getFileName();
$dirname = dirname($this->filePath);
//检查文件大小是否超出限制
if (!$this->checkSize()) {
$this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
return;
}
//创建目录失败
if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
$this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
return;
} else if (!is_writeable($dirname)) {
$this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
return;
}
//移动文件
if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
$this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
} else { //移动成功
$this->stateInfo = $this->stateMap[0];
}
}
/**
* 拉取远程图片
* @return mixed
*/
private function saveRemote()
{
$imgUrl = htmlspecialchars($this->fileField);
$imgUrl = str_replace("&", "&", $imgUrl);
//http开头验证
if (strpos($imgUrl, "http") !== 0) {
$this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
return;
}
preg_match('/(^https*:\/\/[^:\/]+)/', $imgUrl, $matches);
$host_with_protocol = count($matches) > 1 ? $matches[1] : '';
// 判断是否是合法 url
if (!filter_var($host_with_protocol, FILTER_VALIDATE_URL)) {
$this->stateInfo = $this->getStateInfo("INVALID_URL");
return;
}
preg_match('/^https*:\/\/(.+)/', $host_with_protocol, $matches);
$host_without_protocol = count($matches) > 1 ? $matches[1] : '';
// 此时提取出来的可能是 ip 也有可能是域名,先获取 ip
$ip = gethostbyname($host_without_protocol);
// 判断是否是私有 ip
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
$this->stateInfo = $this->getStateInfo("INVALID_IP");
return;
}
//获取请求头并检测死链
$heads = get_headers($imgUrl, 1);
if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
$this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
return;
}
//格式验证(扩展名验证和Content-Type验证)
$fileType = strtolower(strrchr($imgUrl, '.'));
/*
if (!in_array($fileType, $this->config['allowFiles']) || !isset($heads['Content-Type']) || !stristr($heads['Content-Type'], "image")) {
$this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
return;
}
*/
if (!isset($heads['Content-Type']) || !stristr($heads['Content-Type'], "image")) {
$this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
return;
}
//打开输出缓冲区并获取远程图片
ob_start();
$context = stream_context_create(
array('http' => array(
'follow_location' => false // don't follow redirects
))
);
readfile($imgUrl, false, $context);
$img = ob_get_contents();
ob_end_clean();
preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);
$this->oriName = $m ? $m[1] : "";
$this->fileSize = strlen($img);
// 图片连接中无后缀或者后缀不在允许的范围
if (!in_array($fileType, $this->config['allowFiles'])) {
$imgType = '';
switch ($heads['Content-Type']) {
case self::$imageMimeList['jpeg']:
$imgType = '.jpg';
break;
case self::$imageMimeList['gif']:
$imgType = '.gif';
break;
case self::$imageMimeList['png']:
$imgType = '.png';
break;
case self::$imageMimeList['wbmp']:
$imgType = '.bmp';
break;
default:
$this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
return;
}
$this->fileType = $imgType;
$this->fullName = $this->getFullName() . $imgType;
} else {
$this->fileType = $this->getFileExt();
$this->fullName = $this->getFullName();
}
$this->filePath = $this->getFilePath();
$this->fileName = $this->getFileName();
$dirname = dirname($this->filePath);
//检查文件大小是否超出限制
if (!$this->checkSize()) {
$this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
return;
}
//创建目录失败
if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
$this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
return;
} else if (!is_writeable($dirname)) {
$this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
return;
}
//移动文件
if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
$this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
} else { //移动成功
$this->stateInfo = $this->stateMap[0];
}
}
/**
* 上传错误检查
* @param $errCode
* @return string
*/
private function getStateInfo($errCode)
{
return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
}
/**
* 获取文件扩展名
* @return string
*/
private function getFileExt()
{
return strtolower(strrchr($this->oriName, '.'));
}
/**
* 重命名文件
* @return string
*/
private function getFullName()
{
//替换日期事件
$t = time();
$d = explode('-', date("Y-y-m-d-H-i-s"));
$format = $this->config["pathFormat"];
$format = str_replace("{yyyy}", $d[0], $format);
$format = str_replace("{yy}", $d[1], $format);
$format = str_replace("{mm}", $d[2], $format);
$format = str_replace("{dd}", $d[3], $format);
$format = str_replace("{hh}", $d[4], $format);
$format = str_replace("{ii}", $d[5], $format);
$format = str_replace("{ss}", $d[6], $format);
$format = str_replace("{time}", $t, $format);
//过滤文件名的非法字符,并替换文件名
$oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
$oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
$format = str_replace("{filename}", $oriName, $format);
//替换随机字符串
$randNum = rand(1, 10000000000) . rand(1, 10000000000);
if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
$format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
}
$ext = $this->getFileExt();
return $format . $ext;
}
/**
* 获取文件名
* @return string
*/
private function getFileName()
{
return substr($this->filePath, strrpos($this->filePath, '/') + 1);
}
/**
* 获取文件完整路径
* @return string
*/
private function getFilePath()
{
$fullname = $this->fullName;
$rootPath = $_SERVER['DOCUMENT_ROOT'];
if (substr($fullname, 0, 1) != '/') {
$fullname = '/' . $fullname;
}
return $rootPath . $fullname;
}
/**
* 获取临时文件夹路径
* @return string
*/
private function getFileTmpPath()
{
$rootPath = $_SERVER['DOCUMENT_ROOT'];
$tmpPath = $this->config["tmpPathFormat"];
if (substr($tmpPath, 0, 1) != '/') {
$tmpPath = '/' . $tmpPath;
}
return $rootPath . $tmpPath;
}
/**
* 文件类型检测
* @return bool
*/
private function checkType()
{
return in_array($this->getFileExt(), $this->config["allowFiles"]);
}
/**
* 文件大小检测
* @return bool
*/
private function checkSize()
{
return $this->fileSize <= ($this->config["maxSize"]);
}
/**
* 获取当前上传成功文件的各项信息
* @return array
*/
public function getFileInfo()
{
// 分片上传时
if (is_array($this->stateInfo) && $this->stateInfo["state"] == "CHUNK") {
return array($this->stateInfo);
}
return array(
"state" => $this->stateInfo,
"url" => $this->fullName,
"title" => $this->fileName,
"original" => $this->oriName,
"type" => $this->fileType,
"size" => $this->fileSize
);
}
}