前端直传OSS对象存储(多图,多标签上传)

本文依赖阿里文档:https://help.aliyun.com/document_detail/31926.html

代码封装为实现单个页面多图片上传

代码下载:

1.签名在前端完成:点击下载

2.签名在PHP完成(推荐):点击下载

这里主要是针对第二种直传做修改

首先下载第二种压缩包;,解压

把文件复制到项目里,可以访问就好

样式自己改

首先封装验签方法,用于前端ajax调用

format(DateTime::ISO8601);
        $pos = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);
        return $expiration."Z";
    }
    function getAuth(){
    $id= 'LTAI*****qX5h';
    $key= '6dLVHccMdh***vlPDbIdxf6nh';
    $host = 'http://abcd.oss-cn-hangzhou.aliyuncs.com/';

    $now = time();
    $expire = 30; //设置该policy超时时间是30s. 即这个policy过了这个有效时间,将不能访问
    $end = $now + $expire;
    $expiration = gmt_iso8601($end);

    $dir = 'upload-image/';

    //最大文件大小.用户可以自己设置
    $condition = array(0=>'content-length-range', 1=>0, 2=>1048576000);
    $conditions[] = $condition; 

    //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
    $start = array(0=>'starts-with', 1=>'$key', 2=>$dir);
    $conditions[] = $start; 


    $arr = array('expiration'=>$expiration,'conditions'=>$conditions);
    //echo json_encode($arr);
    //return;
    $policy = json_encode($arr);
    $base64_policy = base64_encode($policy);
    $string_to_sign = $base64_policy;
    $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

    $response = array();
    $response['accessid'] = $id;
    $response['host'] = $host;
    $response['policy'] = $base64_policy;
    $response['signature'] = $signature;
    $response['expire'] = $end;
    //这个参数是设置用户上传指定的前缀
    $response['dir'] = $dir;
    echo json_encode($response);
}
?>

 再次封装最主要的上传类

phpUrl = '/get.php'//获取验签数据的方法路径
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", phpUrl, false );
xmlHttp.send( null );
console.log(xmlHttp);
var obj = eval ("(" + xmlHttp.responseText+ ")");
var host = obj['host']
var policyBase64 = obj['policy']
var accessid = obj['accessid']
var signature = obj['signature']
var expire = parseInt(obj['expire'])
var key = obj['dir']
//filenames  用来区分不同的::name,方便后台接收
//filepath   文件上传保存的路劲
function postfile(filenames,filepath) {
        //默认使用后台返回的路径
	if(filepath==''){
		filepath = key;
	}
	$("#container_"+filenames).html('你的浏览器不支持flash,Silverlight或者HTML5!选择文件开始上传');
	var objs = timestamp();
    var storeAs = filepath+objs;  //命名空间
    var uploader = new plupload.Uploader({

	runtimes : 'html5,flash,silverlight,html4',
	browse_button : 'selectfiles_'+filenames,
    //runtimes : 'flash',
	container: document.getElementById('container_'+filenames),
	flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
	silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',

    url : host,

	multipart_params: {
		'Filename':objs + '${filename}',
        'key' : storeAs + '${filename}',
		'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '201', //让服务端返回201,不然收不到上传到OSS返回的数据
		'signature': signature,
	},

	init: {
		PostInit: function() {
			document.getElementById('ossfile_'+filenames).innerHTML = '';
			document.getElementById('postfiles_'+filenames).onclick = function() {
				uploader.start();
				return false;
			};
		},

		FilesAdded: function(up, files) {
			plupload.each(files, function(file) {
				document.getElementById('ossfile_'+filenames).innerHTML = '
' + file.name + ' (' + plupload.formatSize(file.size) + ')' +'
' //--插入input保存标签name提交图片链接(根据自己需求修改name值,filenames最好不要动,这个是用来区分不同的图片上传的)--// +'
'; }); }, UploadProgress: function(up, file) { var d = document.getElementById(file.id); d.getElementsByTagName('b')[0].innerHTML = '' + file.percent + "%"; var prog = d.getElementsByTagName('div')[0]; var progBar = prog.getElementsByTagName('div')[0] progBar.style.width= 2*file.percent+'px'; progBar.setAttribute('aria-valuenow', file.percent); }, FileUploaded: function(up, file, info) { if (info.status >= 200 || info.status < 200) { var str=info.response; //创建文档对象 var parser=new DOMParser(); var xmlDoc=parser.parseFromString(str,"text/xml"); //提取数据 var countrys = xmlDoc.getElementsByTagName('Key'); //注释的部分可自行打印,查看数据 //var location = xmlDoc.getElementsByTagName('Location'); // var arr = []; //arr.push(countrys[0].textContent);//返回不到域名的图片链接 // arr.push(location[0].textContent);//返回带域名的数据,可以用来做前端图片展示 $('#'+file.id+'_1').val(countrys[0].textContent); $('#'+file.id).html(countrys[0].textContent+" | 上传成功"); // document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '上传成功'; } else { document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response; } }, Error: function(up, err) { document.getElementById('console_'+filenames).appendChild(document.createTextNode("\nError xml:" + err.response)); } } }); uploader.init(); } /** * 生成文件名 * @returns */ function timestamp(){ var time = new Date(); var y = time.getFullYear(); var m = time.getMonth()+1; var d = time.getDate(); var h = time.getHours(); var mm = time.getMinutes(); var s = time.getSeconds(); return ""+y+add0(m)+add0(d)+add0(h)+add0(mm)+add0(s); } function add0(m){ return m<10?'0'+m : m; }

 前端html代码和js掉用

前端直传OSS对象存储(多图,多标签上传)_第1张图片

 

你可能感兴趣的:(第三方接口封装l类)