1 提供上传需要的参数给前端
/**
* 开启文件上传
*
* @return
*/
@GetMapping(value = "/policy")
public RespDTO createTransaction() throws Exception {
//原始方式
OSSClient ossClientForDirect = new OSSClient(jingvideoProperties.getOSSENDPOINT(), jingvideoProperties.getAccessKeyID(), jingvideoProperties.getAppSecret());
String host = "https://" + jingvideoProperties.getStoreName() + "." + jingvideoProperties.getOSSENDPOINT();
String dir = jingvideoProperties.getDir();
Date expiration = PhotoDateUtil.getExpiredDate(2);
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
String postPolicy = ossClientForDirect.generatePostPolicy(expiration, policyConds);
byte[] binaryData = postPolicy.getBytes("utf-8");
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
String postSignature = ossClientForDirect.calculatePostSignature(postPolicy);
Map<String, String> respMap = new LinkedHashMap<String, String>();
respMap.put("accessid", jingvideoProperties.getAccessKeyID());
respMap.put("policy", encodedPolicy);
respMap.put("signature", postSignature);
respMap.put("dir", dir);
respMap.put("host", host);
respMap.put("expire", String.valueOf(expiration.getTime() / 1000));
return RespDTO.onSuc(respMap);
}
2 上传成功后阿里云调 回调接口,ossCallbackBody是自定义的参数
/**
* 提供给oss服务器回调的地址
* @param ossCallbackBody
* @param authorization
* @param publicKeyUrlBase64
* @param request
* @param response
* @return
*/
@RequestMapping(value = "oss/callback", method = {RequestMethod.POST,RequestMethod.GET})
public String callback(@RequestBody String ossCallbackBody,
@RequestHeader("Authorization") String authorization,
@RequestHeader("x-oss-pub-key-url") String publicKeyUrlBase64,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
logger.info("ossCallbackBody:{}", ossCallbackBody);
logger.info("authorization:{}",authorization);
logger.info("publicKeyUrlBase64:{}", publicKeyUrlBase64);
//验证是不是oss发过来的回调请求
boolean isOssCallback = CallbackUtil.VerifyOSSCallbackRequest(request, ossCallbackBody);
if (isOssCallback) {
JSONObject jsonObject = JSON.parseObject(ossCallbackBody);
Integer id = Integer.valueOf(jsonObject.get("albumId").toString());
String key = (String) jsonObject.get("objectKey");
videoService.insertVideo(id, key);
response.setStatus(HttpServletResponse.SC_OK);
logger.info("oss/callback==================== : success");
JSONObject json = new JSONObject();
json.put("success",true);
return json.toString();
} else {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
logger.info("oss/callback=============== : false");
JSONObject json = new JSONObject();
json.put("success",false);
return json.toString();
}
}
3阿里云jdk的工具类,用来验证签名(是否是阿里云oss的回调请求)
package com.jingdaka.photo_backend.utils;
import com.aliyun.oss.common.utils.BinaryUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
public class CallbackUtil {
public static boolean VerifyOSSCallbackRequest(HttpServletRequest request, String ossCallbackBody) throws NumberFormatException, IOException
{
boolean ret = false;
String autorizationInput = new String(request.getHeader("Authorization"));
String pubKeyInput = request.getHeader("x-oss-pub-key-url");
byte[] authorization = BinaryUtil.fromBase64String(autorizationInput);
byte[] pubKey = BinaryUtil.fromBase64String(pubKeyInput);
String pubKeyAddr = new String(pubKey);
if (!pubKeyAddr.startsWith("http://gosspublic.alicdn.com/") && !pubKeyAddr.startsWith("https://gosspublic.alicdn.com/"))
{
System.out.println("pub key addr must be oss addrss");
return false;
}
String retString = executeGet(pubKeyAddr);
retString = retString.replace("-----BEGIN PUBLIC KEY-----", "");
retString = retString.replace("-----END PUBLIC KEY-----", "");
String queryString = request.getQueryString();
String uri = request.getRequestURI();
String decodeUri = java.net.URLDecoder.decode(uri, "UTF-8");
String authStr = decodeUri;
if (queryString != null && !queryString.equals("")) {
authStr += "?" + queryString;
}
authStr += "\n" + ossCallbackBody;
ret = doCheck(authStr, authorization, retString);
return ret;
}
public static boolean doCheck(String content, byte[] sign, String publicKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = BinaryUtil.fromBase64String(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature.getInstance("MD5withRSA");
signature.initVerify(pubKey);
signature.update(content.getBytes());
boolean bverify = signature.verify(sign);
return bverify;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@SuppressWarnings({ "finally" })
public static String executeGet(String url) {
BufferedReader in = null;
String content = null;
try {
// 定义HttpClient
@SuppressWarnings("resource")
DefaultHttpClient client = new DefaultHttpClient();
// 实例化HTTP方法
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
content = sb.toString();
} catch (Exception e) {
} finally {
if (in != null) {
try {
in.close();// 最后要关闭BufferedReader
} catch (Exception e) {
e.printStackTrace();
}
}
return content;
}
}
}