cupload插件文件目录
将源码放置于php环境下打开index.html,将会出现以下内容
(本人直接放在了wampserver服务器下的www目录,可参考)
该插件提供了post、异步上传两种方式,下面我一一介绍给大家
1、post方式上传图片
首先要在html文件里引入static文件夹下的js文件夹下的cupload.js
如下:
<script src="static/js/cupload.js"></script>
html
<form method="post" action="./form.php">
<div id="cupload-7"></div>
<button type="submit">提交</button>
</form>
js
var cupload7 = new Cupload ({
ele : '#cupload-7',
name: 'image',
num : 3,
});
php
<?php
//form提交,post提交过来的image是数组
//接收post传来的base64
$base64Arr = $_POST['image'];
$arr = array();
foreach ($base64Arr as $key => $base64) {
//post的数据里面,加号会被替换为空格,需要重新替换回来,如果不是post的数据,则注释掉这一行
$base64Image = str_replace(' ', '+', $base64);
//匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64Image, $result)){
//获取后缀
$type = $result[2];
//设置保存路径
$filePath = "./upload/";
if(!file_exists($filePath)){
mkdir($filePath, 0755);
}
//设置文件名
$fileName = uniqid() . rand(0000,9999);
//设置图片路径
$newFile = $filePath.$fileName.".{$type}";
//存放图片
if (file_put_contents($newFile, base64_decode(str_replace($result[1], '', $base64Image)))){
//返回文件路径
array_push($arr, $newFile);
}else{
die("error");
}
}else{
die("error");
}
}
echo('你提交的图片存放在了:' . implode(',', $arr));die;
注意:注意修改图片上传后存放的路径$filePath
,这个因人而异,需要修改.
2、异步方式上传图片
同样的先引入cupload.js,.同上,在此不多赘述
html
<p>异步上传(3张)[请在php环境下运行,否则会出现未知错误]</p>
<div id="cupload-3"></div>
js
var cupload3 = new Cupload ({
ele : '#cupload-3',
name : 'image',
num : 3,
url : './upload.php',
});
注意:这里url里面的地址,就是指向图片上传的php文件,本人因为使用的是tp(thinkphp)所以在此使用的U方法来对应控制器中的方法
php
<?php
//异步上传,post提交过来的image是字符串
//接收post传来的base64
$base64Str = $_POST['image'];
//post的数据里面,加号会被替换为空格,需要重新替换回来,如果不是post的数据,则注释掉这一行
$base64Image = str_replace(' ', '+', $base64Str);
//匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64Image, $result)){
//获取后缀
$type = $result[2];
//设置保存路径
$filePath = "./upload/";
if(!file_exists($filePath)){
mkdir($filePath, 0755);
}
//设置文件名
$fileName = uniqid() . rand(0000,9999);
//设置图片路径
$newFile = $filePath.$fileName.".{$type}";
//存放图片
if (file_put_contents($newFile, base64_decode(str_replace($result[1], '', $base64Image)))){
//返回文件路径
die($newFile);
}else{
die("error");
}
}else{
die("error");
}
同样需要注意更改自己存放上传图片对应的路径
总结:为了避免大家“步我的后尘”,有写坑需要在此说明。
1、一定要把项目部署到php环境下,本人将项目放在了wampserver服务器www目录下,希望大家可以借鉴。网上有许多wamp安装教程,耐心安装。
2、js中的属性请先别随意更改,等项目成功运行后,再究其源码。
3、上传文件对应的存放路径$filePath
,注意该属性