看这里就知道我在干什么了Ajax和OSS文件上传、删除
这里进行第二种方案的代码演示
我没有进行测试,理论上应该是正确的。。。
首先是前端页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="?" method="post" enctype="multipart/form-data">
<div>
<input type="hidden">
<input type="file">
<button type="button">上传按钮</button>
</div>
<div>
<input type="hidden">
<input type="file">
<button type="button">上传按钮</button>
</div>
<div>
<span>提交按钮</span>
</div>
<script type="text/javascript">
$("span").click(function () {
var object="";
$("input[type='hidden']").each(function (index,element) {
object+=$(this).val()+",";
});
object=object.substring(0,object.length-1);
var url="{:U('Index/index')}";
$.post(url,{"object":object},function () {
alert("上传成功");
});
});
</script>
</form>
<script src="/Public/JS/dist/js/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$("button").click(function () {
var url="{:U('Second/uploadImage')}";
$.ajax({
url: url,
type: "POST",
data: formData,
/**
*必须false才会自动加上正确的Content-Type
*/
contentType: false,
/**
* 必须false才会避开jQuery对 formdata 的默认处理
* XMLHttpRequest会对 formdata 进行正确的处理
*/
processData: false,
success: function (data) {
__this.prevAll("input[type='hidden']").val(data);
alert("上传成功");
},
error: function () {
alert("error");
}
});
});
</script>
</body>
</html>
之后是后台部分代码,注意,这里需要对OSS的SDK文档中的Image.class.php进行一些修改,就是在其中添加两个新的方法,便于我们在一段代码中对两个bucket进行操作:
// 自己编写的
public function uploadImage2($bucketName,$dir,$file){
// $bucketName=Common::getBucketName();
$imgUrl=array();
if(is_array($file['name'])){
foreach($file['name'] as $k=>$v){
$object=$dir.date('Ymd')."/".uniqid().".".substr($file['name'][$k],-3);
$imgUrl[$k]=$object;
$this->ossClient->uploadFile($bucketName, $object, $file['tmp_name'][$k]);
}
}else{
$object=$dir.date('Ymd')."/".uniqid().".".substr($file['name'],-3);
$imgUrl=$object;
$this->ossClient->uploadFile($bucketName, $object, $file['tmp_name']);
}
return $imgUrl;
}
public function delImage2($bucketName,$object){
if($this->ossClient->deleteObject($bucketName, $object)){
return true;
}else{
return false;
}
}
原先部分是直接使用Common中的getBucketName()函数来指定bucket的,但是这里我们需要人为指定,所以把bucket作为参数传入函数中。
最后是控制器部分代码:
<?php
/**
* Created by PhpStorm.
* User: root
* Date: 17-5-18
* Time: 下午3:27
*/
namespace Home\Controller;
use Think\Controller;
use Vendor\OSS\Image;
use Vendor\OSS\OssClient;
class SecondController extends Controller{
private $accessKeyId="你以为我会写出来吗?";
private $accessKeySecret="你是傻子吗?";
private $endPoint="为什么你还会看这里?";
public function index(){
if(IS_POST){
$object_String=I("post.object");
$object_array=explode(",",$object_String);
$oss=new OssClient($this->accessKeyId,$this->accessKeySecret,$this->endPoint);
foreach ($object_array as $value){
$oss->copyObject("temp_bucket",$value,"Fianl_Bucket",$value);
}
}
$this->display();
}
public function uploadImage(){
$image=new Image();
$key=array_keys($_FILES)[0];
$objectUrl=$image->uploadImage2("temp_bucket","Goods/",$_FILES[$key]);
$this->ajaxReturn($objectUrl);
}
}
?>