1.對象存儲概述
????????文件上傳,是指將本地圖片、視頻、音頻等文件上傳到服務器上,可以供其他用戶瀏覽或下載的過程。文件上傳在項目中應用非常廣泛,我們經常發抖音、發朋友圈都用到了文件上傳功能。
實現文件上傳服務,需要有存儲的支持,解決方案有以下幾種:
存儲方式 | 優點 | 缺點 |
---|---|---|
直接保存到硬盤 | 開發便捷,成本低 | 擴容困難 |
分布式文件系統 | 容易實現擴容 | 開發復雜,需要成熟產品支持 |
第三方存儲服務 | 開發簡單,強大功能, 免維護 | 付費 |
2.阿里云對象存儲OSS
阿里云登錄 - 歡迎登錄阿里云,安全穩定的云計算服務平臺歡迎登錄阿里云,全球領先的云計算及人工智能科技公司,阿里云為200多個國家和地區的企業、開發者和政府機構提供云計算基礎服務及解決方案。阿里云云計算、安全、大數據、人工智能、企業應用、物聯網等云計算服務。https://oss.console.aliyun.com/
2.1 阿里云對象存儲OSS配置
2.1.1 創建OSS Bucket
????????登錄阿里云控制臺,申請ECS服務器、申請對象存儲OSS、在OSS管理頁面創建一個Bucket,Bucket是存儲空間的容器,類似于文件夾。選擇Bucket的地域、訪問權限等設置。
2.1.2 獲取AccessKey
????????在阿里云控制臺獲取AccessKey ID和AccessKey Secret,這是訪問OSS的憑證。
2.2 項目中使用對象存儲OSS
2.2.1 配置AccessKey ID和AccessKey Secret
sky:alioss:endpoint: oss-cn-chengdu.aliyuncs.comaccess-key-secret: B4CZYBn9zyoKjQzdN5sQNvdxaWJSuyaccess-key-id: LTAI5tAKNiTtEJaPdE3omMi3bucket-name: luobeilearn
2.2.2 配置配置類
@Configuration
@Slf4j
public class OssConfiguration {@Bean@ConditionalOnMissingBeanpublic AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){log.info("開始上傳阿里云文件上傳工具類對象:{}",aliOssProperties);return new AliOssUtil(aliOssProperties.getEndpoint(),aliOssProperties.getAccessKeyId(),aliOssProperties.getAccessKeySecret(),aliOssProperties.getBucketName());}
}
2.2.3 創建阿里云屬性類
@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;}
2.2.4 創建工具類
@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class AliOssUtil {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;/*** 文件上傳** @param bytes* @param objectName* @return*/public String upload(byte[] bytes, String objectName) {// 創建OSSClient實例。OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);try {// 創建PutObject請求。ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));} catch (OSSException oe) {System.out.println("Caught an OSSException, which means your request made it to OSS, "+ "but was rejected with an error response for some reason.");System.out.println("Error Message:" + oe.getErrorMessage());System.out.println("Error Code:" + oe.getErrorCode());System.out.println("Request ID:" + oe.getRequestId());System.out.println("Host ID:" + oe.getHostId());} catch (ClientException ce) {System.out.println("Caught an ClientException, which means the client encountered "+ "a serious internal problem while trying to communicate with OSS, "+ "such as not being able to access the network.");System.out.println("Error Message:" + ce.getMessage());} finally {if (ossClient != null) {ossClient.shutdown();}}//文件訪問路徑規則 https://BucketName.Endpoint/ObjectNameStringBuilder stringBuilder = new StringBuilder("https://");stringBuilder.append(bucketName).append(".").append(endpoint).append("/").append(objectName);log.info("文件上傳到:{}", stringBuilder.toString());return stringBuilder.toString();}
}
2.2.5 在Controller中使用
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {@Autowiredprivate AliOssUtil aliOssUtil;@PostMapping("/upload")@ApiOperation("文件上傳")public Result<String> upload(MultipartFile file){log.info("文件上傳");try {//原始文件名String originalFilename = file.getOriginalFilename();//截取原始文件名后綴String substring = originalFilename.substring(originalFilename.lastIndexOf("."));String objectName = UUID.randomUUID().toString()+substring;String filePath = aliOssUtil.upload(file.getBytes(),objectName);return Result.success(filePath);} catch (IOException e) {log.error("文件上傳失敗:{}",e);}return Result.error(MessageConstant.UPLOAD_FAILED);}
}