现在阿里云供应了工具存储云做事(OSS),非常方便APP直接将图片等文件上传上去,并供应了多种浏览、下载的办法,不仅操作大略、而且效率高、速率快,本文先容三种利用办法,希望能够让工程师少走弯路。
传统模式这种办法只是把OSS作为文件存储体替代了自建存储器,上传逻辑和路径还是和传统的办法同等,后端做事给前端供应上传接口,在收到前端上传的文件后,再调用阿里云的OSS SDK的API将文件上传到阿里云的OSS存储桶中。
上传流程
详细解释及干系代码请参考《云平台工具存储OSS》
直接表单办法这种办法更加的便捷、快速,无需开拓吸收后端做事,而是前端直接将文件上传到OSS,这种办法就哀求前端按照约定的参数访问OSS API,为了安全起见要按照阿里云SDK的办法天生相应的署名并供应给前端。
FORM表单直接上传流程
这里哀求提前天生署名串,天生算法如下:
package aliyun;import aliyun.pojo.ResultData;import aliyun.pojo.SignatureData;import com.alibaba.fastjson.JSONObject;import org.apache.commons.codec.binary.Base64;public class Controller { private final static String POLICY=34;{\"expiration\":\"2025-12-31T23:59:59Z\",\"conditions\":[[\"content-length-range\",0,104857600]]}"; private String accessKeySecret = System.getenv("ACCESS_SECRET_CODE"); public String signatureCode(int times) throws Exception { ResultData resultData=new ResultData(); //约束规则 String encodePolicy = new String(Base64.encodeBase64(POLICY.getBytes())); // 天生署名。 String signatureCom = com.aliyun.oss.common.auth.ServiceSignature.create().computeSignature(accessKeySecret, encodePolicy); SignatureData signatureData=new SignatureData(encodePolicy,signatureCom); resultData.setData(signatureData); return JSONObject.toJSONString(resultData); }}
个中:POLICY定义了上传有效韶光和文件大小约束,署名要用到阿里云账号的Access Key Secret。这里的署名是有时效性的,有效期内不会改变,如果对安全哀求很高,可以将该署名过程作为做事发布,让前端每次在上传的时候调用做事获取实时的署名数据。
前端form表单的构成如下:
<div id="upload"> <form action="http://mybucket.oss-cn-beijing.aliyuncs.com" method="post" enctype="multipart/form-data"> <p>阿里云AccessKeyID:<input type="text" name="OSSAccessKeyId" value="LTAI8N5XX8cr"></p> <p>约束规则base64:<input type="text" name="policy" value=39;eyJleHBpcmF0aW9uIzMVQyMzo1OTo1OVoiLCJjb25kaXRpb25zIjpbWyJjb250ZW50LWxlbmd0aC1yYW5nZSIsMCwxMDQ4NTc2MDBdXX0='></p> <p>约束规则署名:<input type="text" name="Signature" value="pgxE8VnN8kSJEWzQV7uBE="></p> <p>OSS存储文件名:<input type="text" name="key" value="upload/lee.jpg"></p> <p>选择上传文件:<input name="file" type="file" id="file"></p> <input name="submit" value="上传" type="submit"> </form></div>
个中:action是你账号下OSS存储桶的endpoint URL,OSSAccessKeyId是你账号下的AccessKey ID,policy是对上传规则约束的base64编码(这里千万不能直策应用你定义的policy字符串,而是该字符串的字节码的base64编码后的结果,即由上面的打算结果供应),Signature便是对policy的署名结果,key是存储到你指定bucket的目录和文件名。
ajax办法通过这种办法可以不刷新页面完成文件直接上传到OSS,建议采取plupload.js插件实现。
<!DOCTYPE html><html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"/><title>OSS web直传</title><link rel="stylesheet" type="text/css" href="style.css"/><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"></head><body><h2>OSS web直传---直接在JS署名</h2><ol><li>基于plupload封装 </li><li>支持html5,flash,silverlight,html4 等协议上传</li><li>可以运行在PC浏览器,手机浏览器,微信</li><li>可以选择多文件上传</li><li>显示上传进度条</li><li>可以掌握上传文件的大小</li><li>最关键的是,让你10分钟之内就能移植到你的系统,实现以上牛逼的功能!
</li><li>把稳一点,bucket必须设置了Cors(Post打勾),不然没有办法上传</li><li>把稳一点,把upload.js 里面的host/accessid/accesskey改成您上传所须要的信息即可</li><li>此方法是直接在前端署名,有accessid/accesskey泄露的风险, 线上生产请利用后端署名例子<a href="https://help.aliyun.com/document_detail/oss/practice/pc_web_upload/js_php_upload.html">点击查看详细文档</a></li></ol><br><form name="theform"> <input type="radio" name="myradio" value="local_name" checked=true/> 上传文件名字保持本地文件名字 <input type="radio" name="myradio" value="random_name" /> 上传文件名字是随机文件名<br/>上传到指定目录:<input type="text" id='dirname' placeholder="如果不填,默认是上传到根目录" size=50></form><h4>您所选择的文件列表:</h4><div id="ossfile">你的浏览器不支持flash,Silverlight或者HTML5!
</div><br/><div id="container"><a id="selectfiles" href="javascript:void(0);" class='btn'>选择文件</a><a id="postfiles" href="javascript:void(0);" class='btn'>开始上传</a></div><pre id="console"></pre><p> </p></body><script type="text/javascript" src="lib/plupload-2.1.2/js/plupload.full.min.js"></script><script type="text/javascript" src="upload.js"></script></html>
upload.js代码如下:
host = 'http://mybucket.oss-cn-beijing.aliyuncs.com';accessid= 'LTAI8NmXX8cr';signature = "pgxE8VWz1jKv7cQV7uBE=";policyBase64 = "eyJleHBpcmF0aW9uIjoiMjAyNS0xMi0zMVQyMzo1OTo1OVoiLCJjb25kaXRpb25zIjpbWyJjb250ZW50LWxlbmd0aC1yYW5nZSIsMCwxMDQ4NTc2MDBdXX0=";g_dirname = ''g_object_name = ''g_object_name_type = ''now = timestamp = Date.parse(new Date()) / 1000; function check_object_radio() { var tt = document.getElementsByName('myradio'); for (var i = 0; i < tt.length ; i++ ) { if(tt[i].checked) { g_object_name_type = tt[i].value; break; } }}function get_dirname(){ dir = document.getElementById("dirname").value; if (dir != '' && dir.indexOf('/') != dir.length - 1) { dir = dir + '/' } //alert(dir) g_dirname = dir}function random_string(len) { len = len || 32; var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; var maxPos = chars.length; var pwd = ''; for (i = 0; i < len; i++) { pwd += chars.charAt(Math.floor(Math.random() maxPos)); } return pwd;}function get_suffix(filename) { pos = filename.lastIndexOf('.') suffix = '' if (pos != -1) { suffix = filename.substring(pos) } return suffix;}function calculate_object_name(filename){ if (g_object_name_type == 'local_name') { g_object_name += "${filename}" } else if (g_object_name_type == 'random_name') { suffix = get_suffix(filename) g_object_name = g_dirname + random_string(10) + suffix } return ''}function get_uploaded_object_name(filename){ if (g_object_name_type == 'local_name') { tmp_name = g_object_name tmp_name = tmp_name.replace("${filename}", filename); return tmp_name } else if(g_object_name_type == 'random_name') { return g_object_name }}function set_upload_param(up, filename, ret){ g_object_name = g_dirname; if (filename != '') { suffix = get_suffix(filename) calculate_object_name(filename) } new_multipart_params = { 'key' : g_object_name, 'policy': policyBase64, 'OSSAccessKeyId': accessid, 'success_action_status' : '200', //让做事端返回200,不然,默认会返回204 'signature': signature, }; up.setOption({ 'url': host, 'multipart_params': new_multipart_params }); up.start();}var uploader = new plupload.Uploader({runtimes : 'html5,flash,silverlight,html4',browse_button : 'selectfiles', container: document.getElementById('container'),flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap', url : 'http://oss.aliyuncs.com',init: {PostInit: function() {document.getElementById('ossfile').innerHTML = '';document.getElementById('postfiles').onclick = function() { set_upload_param(uploader, '', false); return false;};},FilesAdded: function(up, files) {plupload.each(files, function(file) {document.getElementById('ossfile').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<b></b>'+'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>'+'</div>';});},BeforeUpload: function(up, file) { check_object_radio(); get_dirname(); set_upload_param(up, file.name, true); },UploadProgress: function(up, file) {var d = document.getElementById(file.id);d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>"; var prog = d.getElementsByTagName('div')[0];var progBar = prog.getElementsByTagName('div')[0]progBar.style.width= 2file.percent+'px';progBar.setAttribute('aria-valuenow', file.percent);},FileUploaded: function(up, file, info) { if (info.status == 200) { document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = 'upload to oss success, object name:' + get_uploaded_object_name(file.name); } else { document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response; } },Error: function(up, err) {document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));}}});uploader.init();
个中:host为OSS存储桶endpoint地址、accessid为阿里云账号ID、signature为后端天生的署名、policyBase64为规则json串的base64编码
访问上传的文件有多种办法可以查看你上传的文件,详细操作见阿里云OSS操作手册。这里只解释一种直接通过URL访问的办法。
针对该bucket设置为开通“静态页面”、权限管理设置为“公共可读”、防盗链设置“referer”等安全选项,然后就可以通过类似
http://mybucket.oss-cn-beijing.aliyuncs.com/upload/lee
的办法访问你上传的图片等文件了。