oss php直传,oss web直传(示例代码)

varexpire=0;

sign_obj=‘‘;varserverUrl=‘auth.php‘;

$(function() {

$("div").on("change",‘input[type="file"]‘,function(evt){

$this=$(this);varfiles=evt.target.files;varfile=files[0];if(file.size> 10*1024*1024){

alert(‘too big‘);return false;

}

get_signature();if(sign_obj== ‘‘) {

alert(sign_obj);

alert(‘签名error,请重试‘);return false;

}varg_object_name=sign_obj.dir+random_string()+get_suffix(file.name);varrequest= newFormData();

request.append("OSSAccessKeyId",sign_obj.accessid);//Bucket 拥有者的Access Key Id。

request.append("policy",sign_obj.policy);//policy规定了请求的表单域的合法性

request.append("Signature",sign_obj.signature);//根据Access Key Secret和policy计算的签名信息,OSS验证该签名信息从而验证该Post请求的合法性

request.append("key",g_object_name);//文件名字,可设置路径

request.append("success_action_status",‘200‘);//让服务端返回200,不然,默认会返回204

request.append(‘x-oss-object-acl‘,‘public-read‘);

request.append(‘file‘, file);

$.ajax({

url : sign_obj.host,//上传阿里地址

data : request,

processData:false,//默认true,设置为 false,不需要进行序列化处理

cache:false,//设置为false将不会从浏览器缓存中加载请求信息

async:false,//发送同步请求

contentType:false,//避免服务器不能正常解析文件---------具体的可以查下这些参数的含义

dataType:‘xml‘,//不涉及跨域 写json即可

type :‘post‘,

success :function(callbackHost, request) {//callbackHost:success,request中就是 回调的一些信息,包括状态码什么的

varorigin=sign_obj.host+‘/‘+g_object_name;varsrc=origin;

$this.closest(‘div‘).find(‘img‘).attr(‘src‘, src).show();

$this.closest(‘div‘).find(‘.imgclose‘).show();

},

error :function(returndata) {

console.log("return data:"+returndata);

alert(‘上传图片出错啦,请重试‘)

}

});

});

})functionrandom_string(len) {

len=len|| 32;varchars= ‘ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678‘;varmaxPos=chars.length;varpwd= ‘‘;for(i= 0; i

pwd+=chars.charAt(Math.floor(Math.random()*maxPos));

}returnpwd;

}functionget_suffix(filename) {varpos=filename.lastIndexOf(‘.‘)varsuffix= ‘‘

if(pos!= -1) {

suffix=filename.substring(pos)

}returnsuffix;

}//获取签名信息

functionsend_request()

{varxmlhttp= null;if(window.XMLHttpRequest)

{

xmlhttp=newXMLHttpRequest();

}else if(window.ActiveXObject)

{

xmlhttp=newActiveXObject("Microsoft.XMLHTTP");

}if(xmlhttp!=null)

{

xmlhttp.open("GET", serverUrl,false);

xmlhttp.send(null);returnxmlhttp.responseText

}else{

alert("Your browser does not support XMLHTTP.");

}

}functionget_signature()

{//可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲

now=timestamp=Date.parse(newDate())/ 1000;if(expire

{varbody=send_request();varobj=JSON.parse(body);if(obj.status==1 &&obj.data.code== 1){

sign_obj=obj.data;

expire=parseInt(sign_obj[‘expire‘]);return true;

}return true;

}return false;

};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值