這兩天學習了一下阿里雲oss圖片存儲java
但願對大有有所幫助git
1,需求花生殼映射本地端口github
2,客戶端上傳代碼服務器
3,服務端獲取簽名 回調代碼學習
4,oss帳號阿里雲
客戶端請求後臺簽名,上傳回調保存信息;url
客戶端代碼 git@github.com:zylovezl/oss-upload.git.net
服務端代碼git@github.com:zylovezl/oss-java.gitserver
客戶端 用阿里雲提供代碼zip包,圖片
修改upload.js
serverUrl = 'http://localhost:8001' 爲本地簽名地址
new_multipart_params = {
'key' : g_object_name,
'policy': policyBase64,
'OSSAccessKeyId': accessid,
'success_action_status' : '200', //讓服務端返回200,否則,默認會返回204
'callback' : callbackbody,
'signature': signature,
'x:my_var':'1'
};
'x:my_var':'1'爲須要傳遞的參數
服務端java
String accessId = ""; // 請填寫您的AccessKeyId。 String accessKey = ""; // 請填寫您的AccessKeySecret。 String endpoint = ""; // 請填寫您的 endpoint。 String bucket = ""; // 請填寫您的 bucketname 。 String host = "http://" + bucket + "." + endpoint; // host的格式爲 bucketname.endpoint // callbackUrl爲 上傳回調服務器的URL,請將下面的IP和Port配置爲您本身的真實信息。 花生殼映射本身註冊 String callbackUrl = "http://2h2566o256.imwork.net:8001"; String dir = "user-dir-prefix/"; // 用戶上傳文件時指定的前綴。
jasonCallback.put("callbackBody","filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}&my_var=${x:my_var}");
&my_var=${x:my_var}爲傳遞的參數
打印的callbackBody
filename=user-dir-prefix%2Fhyd.png&size=190842&mimeType=image%2Fpng&height=1754&width=1240&my_var=1
如何實現oss回調獲取上傳文件的url:
須要設置過時時間
doget()設置過時時間和回調doPOST()時間相同
expirations = DateUtil.parseRfc822Date("Wed, 18 Mar 2019 14:20:00 GMT");
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ossCallbackBody = GetPostBody(request.getInputStream(), Integer.parseInt(request.getHeader("content-length"))); boolean ret = VerifyOSSCallbackRequest(request, ossCallbackBody); String key = ossCallbackBody.split("&")[0].split("=")[1].replace("%2F","/"); String expires = ossCallbackBody.split("&")[1].split("=")[1]; System.out.println("verify result : " +key +"--"+ ret); // System.out.println("OSS Callback Body:" + ossCallbackBody); OSSClient ossClient = new OSSClient(endpoint, accessId, accessKey); java.util.Date expirations = null; try { expirations = DateUtil.parseRfc822Date("Wed, 18 Mar 2019 14:20:00 GMT"); } catch (Exception e) { e.printStackTrace(); } GeneratePresignedUrlRequest requestGenerate = new GeneratePresignedUrlRequest(bucket, key, HttpMethod.GET); requestGenerate.setExpiration(expirations); URL signedUrl = ossClient.generatePresignedUrl(requestGenerate); String path =signedUrl.toString(); if(signedUrl.toString().indexOf("?")>-1){ path = path.substring(0,signedUrl.toString().indexOf("?")); } // 圖片壓縮配置的字符串 String ossurl = "{\"ossurl\":\""+signedUrl.toString()+"\"}"; System.out.println(ossurl); if (ret) { response(request, response, "{\"Status\":\"OK\"}", HttpServletResponse.SC_OK); } else { response(request, response, "{\"Status\":\"verdify not ok\"}", HttpServletResponse.SC_BAD_REQUEST); } }
上面的ossurl就是上傳文件的可訪問路徑