使用阿里云OSS服务器进行web签名直传

来源:互联网 发布:手机上网数据自动关闭 编辑:程序博客网 时间:2024/05/22 09:39

一、在阿里云oss服务器中添加一个Bucket



二、下载oss的sdk文件

地址:https://help.aliyun.com/document_detail/32009.html?spm=5176.doc32008.6.656.1Rzxyl

三、编写后台代码调用oss服务器的方法

其中包含4个方法:生成签名、读取文件、删除、查询文件,下面是代码需要根据自己的oss进行修改相应的参数
import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.InputStream;import java.util.Calendar;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.Map;import java.util.Properties;import net.sf.json.JSONObject;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.aliyun.oss.OSSClient;import com.aliyun.oss.common.utils.BinaryUtil;import com.aliyun.oss.model.MatchMode;import com.aliyun.oss.model.OSSObject;import com.aliyun.oss.model.OSSObjectSummary;import com.aliyun.oss.model.ObjectListing;import com.aliyun.oss.model.ObjectMetadata;import com.aliyun.oss.model.PolicyConditions;public class CopyOfOssUtilsTest {private static Logger log = LoggerFactory.getLogger(CopyOfOssUtilsTest.class);//private static String sourcePath = new UploadToAliFinance().getClass().getResource("/").getPath().toString();//private static Properties p = new Properties();//static {//if(p.isEmpty()) {//String propertyFile = sourcePath + "basesource.properties";//InputStream in;//try {//in = new BufferedInputStream(new FileInputStream(propertyFile));//p.load(in);//} catch (Exception e) {//log.error(e.getMessage(), e);//}//}//}////private static String accessKeyId = p.getProperty("accessKeyId");//private static String accessKeySecret = p.getProperty("accessKeySecret");//private static String endpoint = p.getProperty("endpoint");//private static String endpoint_internal = p.getProperty("endpoint");//private static String bucketName = p.getProperty("bucketName");//private static String callbackHost = p.getProperty("cookieDomain");private static String accessKeyId = "你的accessKeyId";private static String accessKeySecret = "你的accessKeySecret";//阿里云服务器外网地址private static String endpoint = "oss-cn-hangzhou.aliyuncs.com";//阿里云服务器内网地址private static String endpoint_internal = "oss-cn-hangzhou-internal.aliyuncs.com";//使用的bucketprivate static String bucketName = "zhouhuayi1";//回调的域名private static String callbackHost = "local.app.surexing.com";/** * 获取OSS签名 *  * @author zhy * @return */public static JSONObject getOssSign(String callback, Map<String, String> paramMap) {// 创建上传Object的MetadataObjectMetadata meta = new ObjectMetadata();// 设置自定义元信息name的值为my-datameta.addUserMetadata("property", "property-value");// 创建OSSClient实例OSSClient ossClient = null;// 使用访问OSSString dir = "tempfile";String host = "http://" + bucketName + "." + endpoint;JSONObject signJson = null;try {ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);Calendar nowTime = Calendar.getInstance();nowTime.add(Calendar.MINUTE, 5);Date expiration = nowTime.getTime();PolicyConditions policyConds = new PolicyConditions();policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);policyConds.addConditionItem(MatchMode.StartWith,PolicyConditions.COND_KEY, dir);String postPolicy = ossClient.generatePostPolicy(expiration,policyConds);byte[] binaryData = postPolicy.getBytes("utf-8");String encodedPolicy = BinaryUtil.toBase64String(binaryData);String postSignature = ossClient.calculatePostSignature(postPolicy);Map<String, String> respMap = new LinkedHashMap<String, String>();/* 拼接回调函数的参数 */Iterator<String> paramKey = paramMap.keySet().iterator();String paramsUrl = "";while(paramKey.hasNext()) {String key = paramKey.next();paramsUrl += '&' + key + '=' + paramMap.get(key);}if(paramsUrl.length() > 0) {paramsUrl = paramsUrl.substring(1);}respMap.put("accessid", accessKeyId);respMap.put("host", host);respMap.put("policy", encodedPolicy);respMap.put("signature", postSignature);respMap.put("dir", dir);log.debug(respMap.toString());Map<String, Object> callbackMap = new HashMap<String, Object>();callbackMap.put("callbackUrl", callback);callbackMap.put("callbackHost", callbackHost);callbackMap.put("callbackBody", paramsUrl);callbackMap.put("callbackBodyType", "application/x-www-form-urlencoded");byte[] callbackBt = JSONObject.fromObject(callbackMap).toString().getBytes("utf-8");String callbackEncode = BinaryUtil.toBase64String(callbackBt);respMap.put("callback", callbackEncode);respMap.put("expire", String.valueOf(expiration.getTime()));log.debug(callbackMap.toString());signJson = JSONObject.fromObject(respMap);} catch (Exception e) {log.error(e.getMessage(), e);} finally {if(ossClient != null) {ossClient.shutdown();}}return signJson;}/** * 读取文件流 *  * @author zhy * @param key * @return */public static InputStream getOssFileSteam(String key) {OSSClient ossClient = null;try {ossClient = new OSSClient(endpoint_internal, accessKeyId,accessKeySecret);OSSObject ossObject = ossClient.getObject(bucketName, key);return ossObject.getObjectContent();} catch (Exception e) {log.error(e.getMessage(), e);return null;} }/** * 删除oss文件 *  * @author zhy * @param key 文件路径 */public static void deleteOssFile(String key) {OSSClient ossClient = null;try {ossClient = new OSSClient(endpoint_internal, accessKeyId,accessKeySecret);// 删除ObjectossClient.deleteObject(bucketName, key);// 关闭clientossClient.shutdown();} catch (Exception e) {log.debug(e.getMessage(), e);} finally {if(ossClient != null) {ossClient.shutdown();}}}/** * 文件夹搜索 *  * @author zhy * @param keyFolrder 文件夹名 */public static void listFile(String keyFolrder) {OSSClient ossClient = null;try {ossClient = new OSSClient(endpoint_internal, accessKeyId,accessKeySecret);// 列出Object ObjectListing listing = ossClient.listObjects(bucketName, keyFolrder);// 遍历所有Objectfor (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {    System.out.println(objectSummary.getKey());}} catch (Exception e) {log.debug(e.getMessage(), e);} finally {if(ossClient != null) {ossClient.shutdown();}}// 关闭clientossClient.shutdown();}public static void main(String[] args) {listFile("tempfile/sxtk/report/");//deleteOssFile("tempfile/sjtk/report/1497318668549.xlsx");}

四、提供签名接口用于前段调用进行上传(我采用的springmvc 下面是接口的代码)

@Controller@RequestMapping("oss")public class OssUploadController {private static Logger log = LoggerFactory.getLogger(OssUtils.class);/** * 获取oss签名 *  * @param request * @param response * @throws Exception */@RequestMapping(value = "/getSign")public void getOssSign(HttpServletRequest request, HttpServletResponse response) throws Exception {response.setContentType("text/plain;charset=UTF-8");Enumeration<String> keyList = request.getParameterNames();Map<String, String> paramMap = new HashMap<String, String>();while(keyList.hasMoreElements()) {String key = keyList.nextElement();paramMap.put(key, request.getParameter(key));}RiskCookieDto dto = RiskCookiesUtils.getUserInfoDefault(request);paramMap.put("userCode", dto.getUserCode());String callback = paramMap.remove("callback");PrintWriter out = response.getWriter();log.info("回调地址:" + callback);log.info("回调参数:" + paramMap);out.write(OssUtils.getOssSign(callback, paramMap).toString());out.flush();out.close();}@RequestMapping("callback")public void callBack(HttpServletRequest request) {String key = request.getParameter("key");InputStream is = OssUtils.getOssFileSteam(key);try {if (is != null) {    BufferedReader reader = new BufferedReader(new InputStreamReader(is));    while (true) {        String line = reader.readLine();        if (line == null) break;        log.info("\n" + line);    }    is.close();}} catch (IOException e) {log.error(e.getMessage(), e);}}}
前段js需要下载plupload插件https://help.aliyun.com/document_detail/31927.html?spm=5176.doc32009.6.630.Nr4UNj下载及使用的地址
var uploader = null,//上传器accessid = '',//Idhost = '',//主机policyBase64 = '',//policysignature = '',//签名callbackbody = '',//回调内容expire = 0,//过期时间g_object_name_type = '',//类型检测now = Date.parse(new Date()) / 1000,//当前时间isSign = false,//签名状态basePathUrl = window.location.protocol + "//" + window.location.host + "/finance";//获取当前请求地址var isFirst = true;var ossParams = {callbackParams : {},//回调传递的参数filekeyValues : {}, //文件名与上传保存的文件对应集合key为文件名value为上传保存的文件名mimeTypes : [],//上传文件格式设置init : ossUploadInitAction,//上传初始化的操作函数added : ossUploadAddedAction,//上传添加文件后的操作函数before : ossBeforeUploadAction,//上传之前的操作函数progress : ossUploadProgressAction,//上传过程中的操作函数after : ossAfterUploadAction,//上传之后的操作函数error : ossUploadErrorAction//上传失败的操作函数}/** * 初始化oss参数 *  * @author zhy * @param param 参数json */function initParams(param) {if(param["callbackParams"]) {ossParams["callbackParams"] = param["callbackParams"]}if(param["mimeTypes"]) {ossParams["mimeTypes"] = param["mimeTypes"]}if(param["init"]) {ossParams["init"] = param["init"]}if(param["added"]) {ossParams["added"] = param["added"]}if(param["before"]) {ossParams["before"] = param["before"]}if(param["progress"]) {ossParams["progress"] = param["progress"]}if(param["after"]) {ossParams["after"] = param["after"]}if(param["error"]) {ossParams["error"] = param["error"]}}/** * 初始化上传插件 *  * @author zhy * @param selectfilesId 选择文件对象ID */function ossUploadInit(selectfilesId, param) {initParams(param);uploader = new plupload.Uploader({runtimes : 'html5,flash,silverlight,html4',browse_button : selectfilesId,//    multi_selection: false,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',    filters: {        mime_types : ossParams['mimeTypes'],        max_file_size : '10mb', //最大只能上传10mb的文件        prevent_duplicates : true //不允许选取重复文件    },init: {PostInit: function() {ossParams['init']()},FilesAdded: function(up, files) {isFirst = true;ossParams['added'](up, files)},BeforeUpload: function(up, file) {get_signature();ossParams['before'](up, file)},UploadProgress: function(up, file) {ossParams['progress'](up, file)},FileUploaded: function(up, file, info) {ossParams['after'](up, file, info)uploader.refresh();},Error: function(up, error) {ossParams['error'](up, error)uploader.refresh();}}})uploader.init();}/** * 开始上传 *  * @author zhy */function ossStartUpload() {if(filekeyValues[uploader.files[0].name] && isFirst == false) {window.wxc.xcConfirm("不能连续上传同一个文件!", window.wxc.xcConfirm.typeEnum.error);myTipsHiden();} else {isFirst = false;uploader.start();}}/** * 获取服务端签名 *  * @author zhy * @returns {Boolean} */function get_signature() {// 可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲now = timestamp = Date.parse(new Date()) / 1000;if (expire < now + 3) {serverUrl = basePathUrl + '/oss/getSign';    $.ajax({      type:'post',      url:serverUrl,      data:ossParams["callbackParams"],      dataType:'json',      async : false,      success:function(result) {      host = result['host']      policyBase64 = result['policy']      accessid = result['accessid']      signature = result['signature']      expire = parseInt(result['expire'])      callbackbody = result['callback']      }});return true;}return false;};/** * 获取后缀名 *  * @author zhy * @param filename 文件名 * @returns {String} */function get_suffix(filename) {    pos = filename.lastIndexOf('.')    suffix = ''    if (pos != -1) {        suffix = filename.substring(pos)    }    return suffix;}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 ossUploadInitAction() {console.info('上传初始化操作函数');}function ossUploadAddedAction(up, files) {console.info("添加的操作函数")}function ossBeforeUploadAction(up, file) {console.info("上传之前的操作函数")check_object_radio();new_multipart_params = {        'key' : ossParams["filekeyValues"][file.name],        'policy': policyBase64,        'OSSAccessKeyId': accessid,         'success_action_status' : '200', //让服务端返回200,不然,默认会返回204        'callback' : callbackbody,        'signature': signature,    };up.setOption({        'url': host,        'multipart_params': new_multipart_params    });}function ossUploadProgressAction(up, file) {console.info("上传过程中的操作函数");}function ossAfterUploadAction(up, file, info) {if (info.status == 200)    {        console.info('upload to oss success, object name:' + file.name + ' 回调服务器返回的内容是:' + info.response);    }    else if (info.status == 203)    {        console.info('上传到OSS成功,但是oss访问用户设置的上传回调服务器失败,失败原因是:' + info.response);    }    else    {        console.info(info.response);    } }function ossUploadErrorAction(up, err) {console.info("上传出错的操作函数")if (err.code == -600) {        console.error("\n选择的文件太大了,可以根据应用情况,在upload.js 设置一下上传的最大大小");    }    else if (err.code == -601) {        console.error("\n选择的文件后缀不对,可以根据应用情况,在upload.js进行设置可允许的上传文件类型");    }    else if (err.code == -602) {        console.error("\n这个文件已经上传过一遍了");    }    else     {        console.error("\nError xml:" + err.response);    }}




五、调用js调用里面的方法

/** * 获取项目地址 *  * @author zhy * @returns */function getProjectPath() {    var curWwwPath = window.document.location.href;    var pathName = window.document.location.pathname;    var pos = curWwwPath.indexOf(pathName);    var localhostPaht = curWwwPath.substring(0, pos);    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);    return localhostPaht + projectName;}var basePath = getProjectPath();var folderName = "tempfile/sxtk/report";//默认文件夹名var fileNames = "";var filekeyValues = {};var params = {//回调传递的参数callbackParams : {"callback":basePath + "/finance/report/upload"},added : ossUploadAddedAction,//上传添加文件后的操作函数after : ossAfterUploadAction,//上传添加文件后的操作函数error : ossUploadErrorAction,mimeTypes : [{ title : "Exel files", extensions : "xlsx,xls"}]//上传文件格式设置}$(function () {    ossUploadInit("chooseFile", params);})function startUpload() {// 设置参数 此处为回调服务器是传递的参数ossParams["callbackParams"]['timeselect']=timeselect;ossParams["callbackParams"]['yearselect']=yearselect;ossParams["callbackParams"]['typeselect']=typeselect;ossParams["callbackParams"]['reportselect']=reportselect;ossParams["callbackParams"]['custselect']=custselect;ossParams["callbackParams"]['existFlag']=existFlag;ossParams["callbackParams"]['reportType']=reportType;//调用上传方法ossStartUpload();}/** * 选择文件后的方法 *  * @author zhy * @param up 上传对象 * @param file 上传你的文件 */function ossUploadAddedAction(up, files) {plupload.each(files, function(file) {var nowTime = new Date().getTime();var fileName = folderName + '/' + nowTime + get_suffix(file.name);fileNames += "," + fileName;filekeyValues[file.name] = fileName;});fileNames = fileNames.substring(1);$("#uploadFileName").val(files[0].name);ossParams["callbackParams"]["fileNames"] = fileNames;ossParams["filekeyValues"] = filekeyValues;}/** * 上传之后的操作函数 *  * @author zhy * @param up 上传对象 * @param file 上传你的文件 * @param info 返回的信息 */function ossAfterUploadAction(up, file, info) {console.info(info);if (info.status == 200) {var data = eval('(' + info.response + ')');if(data.lackParam && data.lackParam.length > 0) {    var newTab=window.open('about:blank');    var url = basePath + '/finance/report/uploadLackParam?content='+JSON.stringify(data.lackParam);    newTab.location.href = url;    }if (data.flag) {            window.wxc.xcConfirm("文件已上传成功!", window.wxc.xcConfirm.typeEnum.success);        } else {            window.wxc.xcConfirm(data.msg, window.wxc.xcConfirm.typeEnum.error);        }    } else if (info.status == 203) {    console.info('上传到OSS成功,但是oss访问用户设置的上传回调服务器失败,失败原因是:' + info.response);    window.wxc.xcConfirm("文件已上传成功,回调失败!", window.wxc.xcConfirm.typeEnum.error);    } else {    window.wxc.xcConfirm("文件上传失败!", window.wxc.xcConfirm.typeEnum.error);    }}function ossUploadErrorAction(up, err) {console.info("上传出错的操作函数")if (err.code == -600) {        window.wxc.xcConfirm("选择的文件太大了,可以根据应用情况,在upload.js 设置一下上传的最大大小!", window.wxc.xcConfirm.typeEnum.error);    }    else if (err.code == -601) {        window.wxc.xcConfirm("选择的文件后缀不对,可以根据应用情况,在upload.js进行设置可允许的上传文件类型!", window.wxc.xcConfirm.typeEnum.error);    }    else if (err.code == -602) {        window.wxc.xcConfirm("这个文件已经上传过一遍了!", window.wxc.xcConfirm.typeEnum.error);    }    else     {    window.wxc.xcConfirm("上传出错!", window.wxc.xcConfirm.typeEnum.error);        console.error("\nError xml:" + err.response);    }}





需要注意的是上面两张图中的名字要对应,内容不是很完整这都是项目中代码 片段。有时间会单独写一个出来
阅读全文
0 0
原创粉丝点击