瀏覽代碼

阿里云文件上传

xlongwei 6 年之前
父節點
當前提交
8ec5a9cc2d

+ 1 - 1
ifast.sql

@@ -142,7 +142,7 @@ CREATE TABLE `sys_log` (
   `ip` varchar(64) DEFAULT NULL COMMENT 'IP地址',
   `gmtCreate` datetime DEFAULT NULL COMMENT '创建时间',
   PRIMARY KEY (`id`)
-) ENGINE=InnoDB AUTO_INCREMENT=1035116168353091587 DEFAULT CHARSET=utf8 COMMENT='系统日志';
+) ENGINE=InnoDB AUTO_INCREMENT=1035116168353091587 DEFAULT CHARSET=utf8mb4 COMMENT='系统日志';
 
 -- ----------------------------
 --  Table structure for `sys_menu`

+ 38 - 15
src/main/java/com/ifast/oss/config/OSSConfiguration.java

@@ -1,17 +1,23 @@
 package com.ifast.oss.config;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
 import com.ifast.common.service.ConfigService;
 import com.ifast.oss.support.UploadServer;
+import com.ifast.oss.support.aliyun.AliyunOSSProperties;
+import com.ifast.oss.support.aliyun.AliyunUploadServer;
 import com.ifast.oss.support.local.LocalUploadProperties;
 import com.ifast.oss.support.local.LocalUploaderServer;
 import com.ifast.oss.support.qiniu.QiNiuProperties;
 import com.ifast.oss.support.qiniu.QiNiuUploaderServer;
 import com.qiniu.common.Zone;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
-import org.springframework.cache.annotation.EnableCaching;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
 
 @Configuration
 @EnableCaching
@@ -20,25 +26,42 @@ public class OSSConfiguration {
     @Autowired
     private ConfigService configService;
 
+    private Logger log = LoggerFactory.getLogger(this.getClass());
 
     /**
-     * 七牛上传
+     * 本地上传
      */
     @Bean
-    @ConditionalOnMissingBean(UploadServer.class)
-    public UploadServer qiNiuUploadServer() {
-        QiNiuProperties ossConfig = configService.getOssConfigProperties();
-        return new QiNiuUploaderServer(ossConfig, Zone.zone2());
+    @ConditionalOnProperty(prefix="ifast.oss.local", name="localPath", matchIfMissing=false)
+    public UploadServer localUploadServer(LocalUploadProperties properties) {
+    	if(log.isDebugEnabled()){
+    		log.debug("启用本地上传服务");
+    	}
+        return new LocalUploaderServer(properties);
+    }
+    
+    /**
+     * 阿里云OSS上传
+     */
+    @Bean
+    @ConditionalOnProperty(prefix="ifast.oss.aliyun", name="accessKeySecret", matchIfMissing=false)
+    public UploadServer aliyunUploadServer(AliyunOSSProperties properties) {
+    	if(log.isDebugEnabled()){
+    		log.debug("启用阿里云上传服务");
+    	}
+    	return new AliyunUploadServer(properties);
     }
 
     /**
-     * 本地上传
+     * 七牛上传
      */
     @Bean
     @ConditionalOnMissingBean(UploadServer.class)
-    public UploadServer localUploadServer(LocalUploadProperties properties) {
-        return new LocalUploaderServer(properties);
+    public UploadServer qiNiuUploadServer() {
+    	if(log.isDebugEnabled()){
+    		log.debug("启用七牛云上传服务");
+    	}
+        QiNiuProperties ossConfig = configService.getOssConfigProperties();
+        return new QiNiuUploaderServer(ossConfig, Zone.zone2());
     }
-
-
 }

+ 16 - 0
src/main/java/com/ifast/oss/support/aliyun/AliyunOSSProperties.java

@@ -0,0 +1,16 @@
+package com.ifast.oss.support.aliyun;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+import lombok.Data;
+
+@Data
+@Component
+@ConfigurationProperties(prefix = "ifast.oss.aliyun")
+public class AliyunOSSProperties {
+    private String accessKeyId;
+    private String accessKeySecret;
+    private String bucketName;
+    private String endpoint;
+}

+ 86 - 0
src/main/java/com/ifast/oss/support/aliyun/AliyunUploadServer.java

@@ -0,0 +1,86 @@
+package com.ifast.oss.support.aliyun;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.util.Date;
+
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.time.DateFormatUtils;
+import org.apache.commons.lang3.time.DateUtils;
+
+import com.aliyun.oss.OSS;
+import com.aliyun.oss.OSSClient;
+import com.baomidou.mybatisplus.toolkit.SystemClock;
+import com.ifast.common.exception.IFastException;
+import com.ifast.common.type.EnumErrorCode;
+import com.ifast.oss.support.UploadServer;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * @author xiahongwei 2018年9月13日
+ * @see <a href="https://help.aliyun.com/document_detail/84781.html?spm=a2c4g.11186623.6.690.2101c06dKNaOeu">阿里云文件上传文档</a>
+ */
+@Slf4j
+public class AliyunUploadServer implements UploadServer {
+	
+	private static String accessKeyId;
+	private static String accessKeySecret;
+	private static String bucketName;
+	private static String endpoint;
+	
+	public AliyunUploadServer(AliyunOSSProperties properties) {
+		accessKeyId = properties.getAccessKeyId();
+		accessKeySecret = properties.getAccessKeySecret();
+		bucketName = properties.getBucketName();
+		endpoint = properties.getEndpoint();
+	}
+
+	@Override
+	public String upload(byte[] uploadBytes, String fileName) {
+		String key = generateKey(fileName);
+		return upload(bucketName, key, new ByteArrayInputStream(uploadBytes));
+	}
+	
+	public static String generateKey(String fileName) {
+		//路径格式:yyyymm/name.now.ext,key可以考虑存入sys_file
+		return new StringBuilder(DateFormatUtils.format(new Date(), "yyyyMM"))
+				.append("/").append(FilenameUtils.getBaseName(fileName))
+				.append(".").append(SystemClock.now())
+				.append(".").append(FilenameUtils.getExtension(fileName))
+				.toString();
+	}
+
+	public static String upload(String bucketName, String key, InputStream input) {
+		if(StringUtils.isBlank(bucketName) || StringUtils.isBlank(key) || input==null) {
+			throw new IFastException(EnumErrorCode.FileUploadError.getCodeStr());
+		}
+		
+		OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
+		try {
+			ossClient.putObject(bucketName, key, input);
+	        Date expiration = DateUtils.addYears(new Date(), 10); // 设置URL过期时间为10年
+			String url = ossClient.generatePresignedUrl(bucketName, key, expiration).toString();
+			log.info("阿里云上传文件成功,bucketName:{},key:{},url:{}", bucketName, key, url);
+			return url;
+		}catch(Exception e) {
+			log.warn("阿里云上传文件失败:{},bucketName:{},key:{}", e.getMessage(), bucketName, key);
+			throw new IFastException(EnumErrorCode.FileUploadError.getCodeStr());
+		}finally {
+			ossClient.shutdown();
+		}
+	}
+	
+	// 提供相应参数,复制图片1.jpg到项目ifast目录,即可运行main测试上传
+	public static void main(String[] args) throws FileNotFoundException {
+		accessKeyId = "";
+		accessKeySecret = "";
+		bucketName = "";
+		endpoint = "http://oss-cn-beijing.aliyuncs.com";
+		log.info(upload(bucketName, generateKey("1.jpg"), new FileInputStream(new File("1.jpg"))));
+	}
+}

+ 11 - 2
src/main/resources/application-dev.yml

@@ -17,9 +17,16 @@ ifast:
     jsessionidKey: SESSION
     sessionKeyPrefix: ifast:session
   oss:
+    # local.localPath本地上传(建议使用相对路径),aliyun.accessKeySecret阿里云上传,两个都注释则使用七牛云上传(sys_config.oss_qiniu)
     local:
-      localPath: /Users/Aron/dev_projects/idea/ifast/src/main/resources/static/upload
+      localPath: upload
       rootURL: http://localhost:8088/upload
+    aliyun:
+      accessKeyId: 
+      #accessKeySecret:
+      bucketName: 
+      # endpoint以深圳为例,其它region请按实际情况填写
+      endpoint: http://oss-cn-shenzhen.aliyuncs.com
   sms:
     cacheKey: ifast:cache
     cacheKeyPrefix: sms
@@ -48,7 +55,9 @@ spring:
   datasource:
     type: com.alibaba.druid.pool.DruidDataSource
     driverClassName: com.mysql.jdbc.Driver
-    url: jdbc:mysql://127.0.0.1:3306/ifast-new2?useUnicode=true&characterEncoding=utf8
+    url: jdbc:mysql://127.0.0.1:3306/ifast-new2?useUnicode=true&useSSL=false
+    # 推荐utf8mb4编码以便支持表情字符,sys_log记录系统数据变动需要支持utf8mb4
+    connectionInitSqls: SET NAMES utf8mb4;
     username: root
     password: aron
     initialSize: 1

+ 12 - 4
src/main/resources/application-prod.yml

@@ -1,6 +1,6 @@
 ifast:
   projectName: ifast
-  projectRootURL: http://127.0.0.1:8088/
+  projectRootURL: http://ifast.site/
   demoMode: false
   jwt:
     userPrimaryKey: userId
@@ -17,9 +17,16 @@ ifast:
     jsessionidKey: SESSION
     sessionKeyPrefix: ifast:session
   oss:
+    # local.localPath本地上传(正式环境可使用绝对路径),aliyun.accessKeySecret阿里云上传,两个都注释则使用七牛云上传(sys_config.oss_qiniu)
     local:
-      localPath: /Users/Aron/dev_projects/idea/ifast/src/main/resources/static/upload
-      rootURL: http://localhost:8088/upload
+      localPath: /upload
+      rootURL: http://ifast.site/upload
+    aliyun:
+      accessKeyId: 
+      #accessKeySecret:
+      bucketName: 
+      # endpoint以深圳为例,其它region请按实际情况填写
+      endpoint: http://oss-cn-shenzhen.aliyuncs.com      
   sms:
     cacheKey: ifast:cache
     cacheKeyPrefix: sms
@@ -45,7 +52,8 @@ spring:
   datasource:
     type: com.alibaba.druid.pool.DruidDataSource
     driverClassName: com.mysql.jdbc.Driver
-    url: jdbc:mysql://127.0.0.1:3306/ifast?useUnicode=true&characterEncoding=utf8
+    url: jdbc:mysql://127.0.0.1:3306/ifast?useUnicode=true&useSSL=false
+    connectionInitSqls: SET NAMES utf8mb4;
     username: root
     password: 1024key@root
     initialSize: 1