Parcourir la source

添加oss功能

zhh il y a 6 ans
Parent
commit
61d66f7caa

+ 6 - 0
mall-admin/pom.xml

@@ -78,6 +78,12 @@
             <artifactId>jjwt</artifactId>
             <version>0.9.0</version>
         </dependency>
+        <!-- 阿里云OSS -->
+        <dependency>
+            <groupId>com.aliyun.oss</groupId>
+            <artifactId>aliyun-sdk-oss</artifactId>
+            <version>2.5.0</version>
+        </dependency>
     </dependencies>
     <build>
         <plugins>

+ 23 - 0
mall-admin/src/main/java/com/macro/mall/config/OssConfig.java

@@ -0,0 +1,23 @@
+package com.macro.mall.config;
+
+import com.aliyun.oss.OSSClient;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * Created by macro on 2018/5/17.
+ */
+@Configuration
+public class OssConfig {
+    @Value("${aliyun.oss.endpoint}")
+    private String ALIYUN_OSS_ENDPOINT;
+    @Value("${aliyun.oss.accessKeyId}")
+    private String ALIYUN_OSS_ACCESSKEYID;
+    @Value("${aliyun.oss.accessKeySecret}")
+    private String ALIYUN_OSS_ACCESSKEYSECRET;
+    @Bean
+    public OSSClient ossClient(){
+        return new OSSClient(ALIYUN_OSS_ENDPOINT,ALIYUN_OSS_ACCESSKEYID,ALIYUN_OSS_ACCESSKEYSECRET);
+    }
+}

+ 45 - 0
mall-admin/src/main/java/com/macro/mall/controller/OssController.java

@@ -0,0 +1,45 @@
+package com.macro.mall.controller;
+
+
+import com.macro.mall.dto.CommonResult;
+import com.macro.mall.dto.OssCallbackResult;
+import com.macro.mall.dto.OssPolicyResult;
+import com.macro.mall.service.impl.OssServiceImpl;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.*;
+
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * Oss相关操作接口
+ * Created by macro on 2018/4/26.
+ */
+@Controller
+@Api(tags = "OssController",description = "Oss管理")
+@RequestMapping("/aliyun/oss")
+public class OssController {
+	@Autowired
+	private OssServiceImpl ossService;
+
+	@ApiOperation(value = "oss上传签名生成")
+	@RequestMapping(value = "/policy",method = RequestMethod.GET)
+	@ResponseBody
+	public Object policy() {
+		OssPolicyResult result = ossService.policy();
+		return new CommonResult().success(result);
+	}
+
+	/**
+	 * 上传成功回调方法
+	 */
+	@RequestMapping(value = "callback",method = RequestMethod.POST)
+	@ResponseBody
+	public Object callback(HttpServletRequest request) {
+		OssCallbackResult ossCallbackResult = ossService.callback(request);
+		return new CommonResult().success(ossCallbackResult);
+	}
+
+}

+ 34 - 0
mall-admin/src/main/java/com/macro/mall/dto/OssCallbackParam.java

@@ -0,0 +1,34 @@
+package com.macro.mall.dto;
+
+/**
+ * Created by macro on 2018/5/17.
+ */
+public class OssCallbackParam {
+    private String callbackUrl;
+    private String callbackBody;
+    private String callbackBodyType;
+
+    public String getCallbackUrl() {
+        return callbackUrl;
+    }
+
+    public void setCallbackUrl(String callbackUrl) {
+        this.callbackUrl = callbackUrl;
+    }
+
+    public String getCallbackBody() {
+        return callbackBody;
+    }
+
+    public void setCallbackBody(String callbackBody) {
+        this.callbackBody = callbackBody;
+    }
+
+    public String getCallbackBodyType() {
+        return callbackBodyType;
+    }
+
+    public void setCallbackBodyType(String callbackBodyType) {
+        this.callbackBodyType = callbackBodyType;
+    }
+}

+ 52 - 0
mall-admin/src/main/java/com/macro/mall/dto/OssCallbackResult.java

@@ -0,0 +1,52 @@
+package com.macro.mall.dto;
+
+/**
+ * Created by macro on 2018/5/17.
+ */
+public class OssCallbackResult {
+    private String filename;
+    private String size;
+    private String mimeType;
+    private String width;
+    private String height;
+
+    public String getFilename() {
+        return filename;
+    }
+
+    public void setFilename(String filename) {
+        this.filename = filename;
+    }
+
+    public String getSize() {
+        return size;
+    }
+
+    public void setSize(String size) {
+        this.size = size;
+    }
+
+    public String getMimeType() {
+        return mimeType;
+    }
+
+    public void setMimeType(String mimeType) {
+        this.mimeType = mimeType;
+    }
+
+    public String getWidth() {
+        return width;
+    }
+
+    public void setWidth(String width) {
+        this.width = width;
+    }
+
+    public String getHeight() {
+        return height;
+    }
+
+    public void setHeight(String height) {
+        this.height = height;
+    }
+}

+ 61 - 0
mall-admin/src/main/java/com/macro/mall/dto/OssPolicyResult.java

@@ -0,0 +1,61 @@
+package com.macro.mall.dto;
+
+/**
+ * Created by macro on 2018/5/17.
+ */
+public class OssPolicyResult {
+    private String accessKeyId;
+    private String policy;
+    private String signature;
+    private String dir;
+    private String callback;
+    private String action;
+
+    public String getAccessKeyId() {
+        return accessKeyId;
+    }
+
+    public void setAccessKeyId(String accessKeyId) {
+        this.accessKeyId = accessKeyId;
+    }
+
+    public String getPolicy() {
+        return policy;
+    }
+
+    public void setPolicy(String policy) {
+        this.policy = policy;
+    }
+
+    public String getSignature() {
+        return signature;
+    }
+
+    public void setSignature(String signature) {
+        this.signature = signature;
+    }
+
+    public String getDir() {
+        return dir;
+    }
+
+    public void setDir(String dir) {
+        this.dir = dir;
+    }
+
+    public String getCallback() {
+        return callback;
+    }
+
+    public void setCallback(String callback) {
+        this.callback = callback;
+    }
+
+    public String getAction() {
+        return action;
+    }
+
+    public void setAction(String action) {
+        this.action = action;
+    }
+}

+ 14 - 0
mall-admin/src/main/java/com/macro/mall/service/OssService.java

@@ -0,0 +1,14 @@
+package com.macro.mall.service;
+
+import com.macro.mall.dto.OssCallbackResult;
+import com.macro.mall.dto.OssPolicyResult;
+
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * Created by macro on 2018/5/17.
+ */
+public interface OssService {
+    OssPolicyResult policy();
+    OssCallbackResult callback(HttpServletRequest request);
+}

+ 101 - 0
mall-admin/src/main/java/com/macro/mall/service/impl/OssServiceImpl.java

@@ -0,0 +1,101 @@
+package com.macro.mall.service.impl;
+
+import com.aliyun.oss.OSSClient;
+import com.aliyun.oss.common.utils.BinaryUtil;
+import com.aliyun.oss.model.MatchMode;
+import com.aliyun.oss.model.PolicyConditions;
+import com.macro.mall.dto.OssCallbackParam;
+import com.macro.mall.dto.OssCallbackResult;
+import com.macro.mall.dto.OssPolicyResult;
+import com.macro.mall.service.OssService;
+import com.macro.mall.util.JsonUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+import javax.servlet.http.HttpServletRequest;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+/**
+ * Created by macro on 2018/5/17.
+ */
+@Service
+public class OssServiceImpl implements OssService {
+
+	private static final Logger LOGGER = LoggerFactory.getLogger(OssServiceImpl.class);
+	@Value("${aliyun.oss.policy.expire}")
+	private int ALIYUN_OSS_EXPIRE;
+	@Value("${aliyun.oss.maxSize}")
+	private int ALIYUN_OSS_MAX_SIZE;
+	@Value("${aliyun.oss.callback}")
+	private String ALIYUN_OSS_CALLBACK;
+	@Value("${aliyun.oss.bucketName}")
+	private String ALIYUN_OSS_BUCKET_NAME;
+	@Value("${aliyun.oss.endpoint}")
+	private String ALIYUN_OSS_ENDPOINT;
+	@Value("${aliyun.oss.dir.prefix}")
+	private String ALIYUN_OSS_DIR_PREFIX;
+
+	@Autowired
+	private OSSClient ossClient;
+
+	/**
+	 * 签名生成
+	 */
+	@Override
+	public OssPolicyResult policy() {
+		OssPolicyResult result = new OssPolicyResult();
+		// 存储目录
+		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
+		String dir = ALIYUN_OSS_DIR_PREFIX+sdf.format(new Date());
+		// 签名有效期
+		long expireEndTime = System.currentTimeMillis() + ALIYUN_OSS_EXPIRE * 1000;
+		Date expiration = new Date(expireEndTime);
+		// 文件大小
+		long maxSize = ALIYUN_OSS_MAX_SIZE * 1024 * 1024;
+		// 回调
+//		OssCallbackParam callback = new OssCallbackParam();
+//		callback.setCallbackUrl(ALIYUN_OSS_CALLBACK);
+//		callback.setCallbackBody("filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
+//		callback.setCallbackBodyType("application/x-www-form-urlencoded");
+		// 提交节点
+		String action = "http://" + ALIYUN_OSS_BUCKET_NAME + "." + ALIYUN_OSS_ENDPOINT;
+		try {
+			PolicyConditions policyConds = new PolicyConditions();
+			policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxSize);
+			policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
+			String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
+			byte[] binaryData = postPolicy.getBytes("utf-8");
+			String policy = BinaryUtil.toBase64String(binaryData);
+			String signature = ossClient.calculatePostSignature(postPolicy);
+//			String callbackData = BinaryUtil.toBase64String(JsonUtil.objectToJson(callback).getBytes("utf-8"));
+			// 返回结果
+			result.setAccessKeyId(ossClient.getCredentialsProvider().getCredentials().getAccessKeyId());
+			result.setPolicy(policy);
+			result.setSignature(signature);
+			result.setDir(dir);
+//			result.setCallback(callbackData);
+			result.setAction(action);
+		} catch (Exception e) {
+			LOGGER.error("签名生成失败", e);
+		}
+		return result;
+	}
+
+	@Override
+	public OssCallbackResult callback(HttpServletRequest request) {
+		OssCallbackResult result= new OssCallbackResult();
+		String filename = request.getParameter("filename");
+		filename = "http://".concat(ALIYUN_OSS_BUCKET_NAME).concat(".").concat(ALIYUN_OSS_ENDPOINT).concat("/").concat(filename);
+		result.setFilename(filename);
+		result.setSize(request.getParameter("size"));
+		result.setMimeType(request.getParameter("mimeType"));
+		result.setWidth(request.getParameter("width"));
+		result.setHeight(request.getParameter("height"));
+		return result;
+	}
+
+}

+ 12 - 1
mall-admin/src/main/resources/application.properties

@@ -36,4 +36,15 @@ jwt.secret=mySecret
 jwt.expiration=604800
 #JWT¸ºÔØÖÐÄõ½¿ªÍ·
 jwt.tokenHead=Bearer 
-#===JWT end===
+#===JWT end===
+
+#===OSS start===
+aliyun.oss.endpoint=oss-cn-shenzhen.aliyuncs.com
+aliyun.oss.accessKeyId=test
+aliyun.oss.accessKeySecret=test
+aliyun.oss.bucketName=macro-oss
+aliyun.oss.policy.expire=300
+aliyun.oss.maxSize=10
+aliyun.oss.callback=http://localhost:8080/aliyun/oss/callback
+aliyun.oss.dir.prefix=mall/images/
+#===OSS end===