2019独角兽企业重金招聘Python工程师标准>>>
这两天学习了一下阿里云oss图片存储
希望对大有有所帮助
1,需求花生壳映射本地端口
2,客户端上传代码
3,服务端获取签名 回调代码
4,oss账号
客户端请求后台签名,上传回调保存信息;
客户端代码 [email protected]:zylovezl/oss-upload.git
服务端代码[email protected]:zylovezl/oss-java.git
客户端 用阿里云提供代码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就是上传文件的可访问路径