springboot使用阿里云OSS的sdk上传文件

springboot使用阿里云OSS的sdk上传文件

阿里云OSS的SDK

<!-- https://mvnrepository.com/artifact/com.aliyun.oss/aliyun-sdk-oss -->
<dependency>
	<groupId>com.aliyun.oss</groupId>
	<artifactId>aliyun-sdk-oss</artifactId>
	<version>3.8.1</version>
</dependency>

上传代码

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDate;
import java.util.UUID;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;


/**
 * 文件上传
 */
@RestController
@RequestMapping("/test/upload")
public class UploadController {

	@PostMapping
	public Object upload (@RequestParam("file")MultipartFile multipartFile) {
		
		// oss 节点
		String endpoint = "oss-cn-hangzhou.aliyuncs.com";
		// oss accessKeyId
		String accessKeyId = "**************************";
		// oss accessKeySecret
		String accessKeySecret = "*************************";
		// oss 存储bucket
		String bucket = "springboot-community";
		// oss 访问域名
		String domain = "https://oss-cn-hangzhou.aliyuncs.com/";
		
		// 本地备份文件夹
		String localFolder = "D:\\upload";
		
		OSS ossClient = null;

		try {
			
			// 初始化 ossClient
			ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

			// 打散目录
			String[] directory = this.getDateFolder();
				
			// 使用UUID重命名文件
			String fileName = UUID.randomUUID().toString().replace("-", "") + "." + this.getSuffix(multipartFile.getOriginalFilename());
			
			// 上传的URI
			String uri = String.join("/", directory[0], directory[1], directory[2], fileName);
			
			// 上传文件
			ossClient.putObject(bucket, uri, multipartFile.getInputStream());
			
			// 序列化到本地备份
			Path path = Paths.get(localFolder, directory);
			if (Files.notExists(path)) {
				// 目录不存在,创建
				Files.createDirectories(path);
			}
			Files.write(path.resolve(fileName), multipartFile.getBytes(), StandardOpenOption.CREATE_NEW);

			// 返回完整的访问地址
			return domain + uri;
		} catch (OSSException | ClientException e) {
			return "文件上传异常";
		} catch (IOException e) {
			return "文件IO异常";
		} finally {
			if (ossClient != null) {
				// 释放资源
				ossClient.shutdown();
			}
		}
	}
	
	/**
	 * 根据当前日期,打散目录
	 * yyyy/MM/dd
	 * @return
	 */
	private String[] getDateFolder() {
		String[] retVal = new String[3];
		
		LocalDate localDate = LocalDate.now();
		retVal[0] = localDate.getYear() + "";
		
		int month = localDate.getMonthValue();
		retVal[1] = month < 10 ? "0" + month : month + "";
		
		int day = localDate.getDayOfMonth();
		retVal[2] = day < 10 ? "0" + day : day + "";
		
		return retVal;
	}

	/**
	 * 获取文件后缀
	 * @param fileName
	 * @return
	 */
	private String getSuffix(String fileName) {
		int index = fileName.lastIndexOf(".");
		if (index != -1) {
			String suffix = fileName.substring(index + 1);
			if (!suffix.isEmpty()) {
				return suffix;
			}
		}
		throw new IllegalArgumentException("非法的文件名称:" + fileName);
	}
}

这里仅仅是演示如何上传。实际环境中,还需要 判断文件的合法性
使用OSS的时候,建议绑定自己的域名,这样对于以后迁移资源到其他服务商,甚至迁移到本地,使用Nginx等web服务器提供服务。都不用修改已经存储在数据库中的资源访问路径。只要修改一下DNS解析即可。