1.在pom.xml中引入amazonS3的依賴。
<dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-s3</artifactId> <version>1.11.792</version> </dependency>
2.controller接口層
package com.example.demo.controller; import com.example.demo.common.result.CodeMsg; import com.example.demo.common.result.Result; import com.example.demo.model.AmazonFileModel; import com.example.demo.service.AmasonService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; 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 javax.servlet.http.HttpServletRequest; import java.util.Map; import java.util.UUID; /** * @Description: TODO * @author: 韓振亞 * @date: 2021年06月09日 14:21 */ @RestController @RequestMapping("/amazonS3") @Slf4j public class AmazonController { /** 雲存儲中的測試數據目錄,不允許刪除 */ final String DEMO = "/demo"; @Autowired AmasonService amazonService; /** * @Description 文件上傳雲存儲 * @Param [file, params] * @return com.zhanglf.common.result.Result<com.zhanglf.model.AmazonFileModel> */ @PostMapping(value = "/upload") public Result<AmazonFileModel> upload(@RequestParam("file") MultipartFile file, @RequestParam("params") String params, HttpServletRequest request){ AmazonFileModel amazonFileModel= null; try{ String uid = UUID.randomUUID().toString(); amazonFileModel= amazonService.upload(file,uid); }catch (Exception e){ log.error("上傳雲存儲Exception",e.getCause()); return Result.error(CodeMsg.SERVER_ERROR.fillArgs(e.getMessage())); } return Result.success(amazonFileModel); } }
3.服務層和服務接口層
package com.example.demo.service; import com.example.demo.model.AmazonFileModel; import org.springframework.web.multipart.MultipartFile; public interface AmasonService { /** * @Description 文件上傳 * @Param [file, uid] * @return com.zhanglf.model.AmazonFileModel */ AmazonFileModel upload(MultipartFile file, String uid); } package com.example.demo.service.impl; import com.amazonaws.AmazonServiceException; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectResult; import com.example.demo.model.AmazonFileModel; import com.example.demo.service.AmasonService; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import javax.annotation.PostConstruct; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; /** * @Description: TODO * @author: 韓振亞 * @date: 2021年06月09日 11:36 */ @Service public class AmazonServiceImpl implements AmasonService { /** bucket */ final String bucketName = "hzy-bucket"; /** accessKey */ final String accessKey = "minioadmin"; /** secretKey */ final String secretKey = "minioadmin"; /** endpoint */ final String endpoint = "http://127.0.0.1:9000"; /** aws s3 client */ AmazonS3 s3 = null; @Override public AmazonFileModel upload(MultipartFile file, String uid) { String tempFileName = file.getOriginalFilename(); String originalFileName = file.getOriginalFilename(); String contentType = file.getContentType(); long fileSize = file.getSize(); String dateDir = new SimpleDateFormat("/yyyy/MM/dd").format(new Date()); String tempBucketName = bucketName+dateDir; String filePath = dateDir+"/"+tempFileName; ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentType(contentType); objectMetadata.setContentLength(fileSize); try { PutObjectResult putObjectResult = s3.putObject(tempBucketName, tempFileName, file.getInputStream(), objectMetadata); } catch (AmazonServiceException e) { System.out.println(e.getErrorMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } AmazonFileModel amazonFileModel = new AmazonFileModel (); amazonFileModel .setFileName(originalFileName); amazonFileModel .setFileSize(fileSize); amazonFileModel .setFileType(contentType); amazonFileModel .setFilePath(filePath); amazonFileModel .setUrl(endpoint+"/"+filePath); return amazonFileModel ; } @PostConstruct public void init(){ ClientConfiguration config = new ClientConfiguration(); AwsClientBuilder.EndpointConfiguration endpointConfig = new AwsClientBuilder.EndpointConfiguration(endpoint, "cn-north-1"); AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey,secretKey); AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials); s3 = AmazonS3Client.builder() .withEndpointConfiguration(endpointConfig) .withClientConfiguration(config) .withCredentials(awsCredentialsProvider) .disableChunkedEncoding() .withPathStyleAccessEnabled(true) .build(); } }
4.相關的實體類
package com.example.demo.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @Description: TODO * @author: 韓振亞 * @date: 2021年06月09日 10:19 */ @Data @AllArgsConstructor @NoArgsConstructor public class AmazonFileModel { /** 文件大小 */ private long fileSize; /** 文件名稱 */ private String fileName; /** 文件URL */ private String url; /** 雲存儲中的路徑 */ private String filePath; /** 文件類型 */ private String fileType; } package com.example.demo.common.result; import lombok.AllArgsConstructor; import lombok.Getter; /** * @Description: TODO * @author: 韓振亞 * @date: 2021年06月09日 10:22 */ @AllArgsConstructor @Getter public class Result<T> { /** * 返回代碼 */ private int code; /** * 返回消息 */ private String msg; /** * 返回數據 */ private T data; /** * 成功時候的調用 * */ public static <T> Result<T> success(T data){ return new Result<T>(0,"success",data); } /** * 成功時候的調用 * */ public static Result success(){ return new Result(0,"success",null); } /** * 失敗時候的調用 * */ public static <T> Result<T> error(CodeMsg codeMsg){ if(codeMsg == null) { return null; } return new Result<T>(codeMsg.getCode(),codeMsg.getMsg(),null); } } package com.example.demo.common.result; import lombok.Getter; /** * @Description: TODO * @author: 韓振亞 * @date: 2021年06月09日 11:30 */ @Getter public class CodeMsg { //通用信息 /** 成功 */ public static CodeMsg SUCCESS = new CodeMsg(0, "success"); /** 服務器異常 */ public static CodeMsg SERVER_ERROR = new CodeMsg(500000,"服務端異常:%s"); /** 參數校驗異常 */ public static CodeMsg BIND_ERROR = new CodeMsg(500001,"參數校驗異常:%s"); /** 傳入參數為空 */ public static CodeMsg PARAMS_IS_EMPTY = new CodeMsg(500002,"傳入參數為空:%s"); /** 參數解析失敗 */ public static CodeMsg PARAMS_PARSE_ERROR = new CodeMsg(500003,"參數解析失敗:%s"); //登錄模塊 5001XX /** 賬號不存在 */ public static CodeMsg ACCOUNT_NOT_EXIST = new CodeMsg(500100,"賬號不存在:%s"); /** 賬號已存在 */ public static CodeMsg ACCOUNT_EXISTS = new CodeMsg(500101,"賬號已存在:%s"); /** 密碼不正確 */ public static CodeMsg PASSWORD_ERROR = new CodeMsg(500102,"密碼不正確:%s"); //權限模塊 5002XX //雲中間件模塊 5003XX /** 雲存儲異常 */ public static CodeMsg OSS_ERROR = new CodeMsg(500300,"雲存儲異常:%s"); /** * 參數為空 */ public static CodeMsg PARAM_EMPTY = new CodeMsg(400001,"參數:%s不能為空!"); /** * 表中已經存在該字段 */ public static CodeMsg FIELD_EXIST = new CodeMsg(400002,"%s"); /** * 狀態為已發布 */ public static CodeMsg PUBLIC_STATUS = new CodeMsg(400003,"狀態為已發布,不允許修改或刪除操作!"); //執行數據庫操作異常模塊 5004XX /**執行新增時數據庫異常*/ public static CodeMsg MYSQL_INSERT_EXCEPTION = new CodeMsg(500401,"執行新增時數據庫異常:%s"); /**執行修改時數據庫異常*/ public static CodeMsg MYSQL_UPDATE_EXCEPTION = new CodeMsg(500402,"執行修改時數據庫異常:%s"); /**執行刪除時數據庫異常*/ public static CodeMsg MYSQL_DELETE_EXCEPTION = new CodeMsg(500403,"執行刪除時數據庫異常:%s"); /**執行查詢時數據庫異常*/ public static CodeMsg MYSQL_QUERY_EXCEPTION = new CodeMsg(500404,"執行查詢時數據庫異常:%s"); /**執行批量插入時插入條數小於入參條數*/ public static CodeMsg MYSQL_BATCH_INSERT_EXCEPTION = new CodeMsg(500405,"批量插入數量不對:%s"); /**數據狀態不允許進行某些操作*/ public static CodeMsg STATUS_ERROR = new CodeMsg(500406,"%s"); /** 返回碼 */ private int code; /** 返回信息 */ private String msg; /** 無參構造方法 */ private CodeMsg() { } /** 構造方法 */ private CodeMsg(int code, String msg) { this.code = code; this.msg = msg; } /** 填充動態參數 */ public CodeMsg fillArgs(Object... args) { int code = this.code; String message = String.format(this.msg, args); return new CodeMsg(code, message); } }
5.修改配置文件上傳文件限制
#設置單個文件的大小 spring.servlet.multipart.max-request-size=50MB #設置單次請求的文件的總大小 spring.servlet.multipart.max-file-size=200MB
6.接口請求測試:postman
接口請求返回值:
{ "code": 0, "msg": "success", "data": { "fileSize": 3226253, "fileName": "3.9智慧應急投標技術方案(華駿)(1)(1).docx", "url": "http://127.0.0.1:9000//2021/06/09/3.9智慧應急投標技術方案(華駿)(1)(1).docx", "filePath": "/2021/06/09/3.9智慧應急投標技術方案(華駿)(1)(1).docx", "fileType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document" } }