Springboot 통합 아 리 클 라 우 드 OSS 업로드 파일 시스템 튜 토리 얼

첫 번 째 단계:아 리 클 라 우 드 OSS 서 비 스 를 개통 하고 Bucket 을 만 들 고 id 와 키 를 가 져 옵 니 다.
在这里插入图片描述
在这里插入图片描述
두 번 째 단계:공식 문서 에 따라 업로드 코드 를 작성 합 니 다.
在这里插入图片描述
1.새 maven 항목
의존 도 추가:

<!--    oss   -->
 <dependency>
 <groupId>com.aliyun.oss</groupId>
 <artifactId>aliyun-sdk-oss</artifactId>
 </dependency>
 <!--         -->
 <dependency>
 <groupId>joda-time</groupId>
 <artifactId>joda-time</artifactId>
 </dependency>
2.application.properties 설정

#    
server.port=8002
#   
spring.application.name=service-oss
#    :dev、test、prod
spring.profiles.active=dev

#    OSS
#      ,                 
aliyun.oss.file.endpoint=your endpoint
aliyun.oss.file.keyid=your accessKeyId
aliyun.oss.file.keysecret=your accessKeySecret
#bucket        ,     java    
aliyun.oss.file.bucketname=guli-file
3.시작 클래스 만 들 기
OssApplication.java 만 들 기

package com.sun.oss;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({"com.sun"})
public class OssApplication {
    public static void main(String[] args) {
        SpringApplication.run(OssApplication.class, args);
    }
}
시작 오류:
在这里插入图片描述
다 중 모듈 을 응용 할 때 이 모듈 은 데이터 베 이 스 를 사용 하지 않 았 고 프로필 에 데이터베이스 설정 정보 가 없 으 면 오류 가 발생 할 수 있 습 니 다.
첫 번 째 방법:
설정 클래스 에 데이터베이스 설정 정 보 를 추가 합 니 다:

# mysql     
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/musicdb?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
두 번 째 방법:주 해 를 추가 하고@SpringBootApplication 주해 에 exclude 를 추가 하여 DataSourceAutoConfiguration 자동 로드 를 해제 합 니 다.

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
4.도구 클래스 만 들 기:
프로필 키 정보 읽 기
ConstantPropertiesUtils.java

//      ,spring  ,spring    ,        
@Component
public class ConstantPropertiesUtils implements InitializingBean {

    //        
    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.keyid}")
    private String keyId;

    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketName;

    //        
    public static String END_POIND;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;

    @Override
    public void afterPropertiesSet() throws Exception {
        END_POIND = endpoint;
        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
        BUCKET_NAME = bucketName;
    }
}
5.controller 클래스 작성

@Api(description = "     oss")
@RestController
@RequestMapping("/eduoss/fileoss")
@CrossOrigin//      
public class OssController {

    @Autowired
    private OssService ossService;

    //       
    @ApiOperation("    ")
    @PostMapping
    public R uploadOssFile(MultipartFile file) {
        //        MultipartFile
        //     oss   
        String url = ossService.uploadFileAvatar(file);
        return R.ok().data("url",url);
    }
}
6.service 클래스 작성

@Service
public class OssServiceImpl implements OssService {
    //    
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //      
        String endPoind = ConstantPropertiesUtils.END_POIND;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        try {
            //  Oss  
            OSS ossClient = new OSSClientBuilder().build(endPoind, accessKeyId, accessKeySecret);

            //         
            InputStream inputStream = file.getInputStream();
            //      
            String filename = file.getOriginalFilename();

            //1.         ,  UUid
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //  fileName
            filename=uuid+filename;

            //2.         
            //      ,    org.joda.time  
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //  
            filename=datePath+"/"+filename;

            //  oss      
            //      Bucket  
            //         oss         
            //             
            ossClient.putObject(bucketName,filename,inputStream);

            //  OssClient
            ossClient.shutdown();

            //           
            //      oss        
            //https://edu-975.oss-cn-beijing.aliyuncs.com/07aef13af7ea82703f3eb320c3f577ec.jpg
            String url="https://"+bucketName+"."+endPoind+"/"+filename;
            return url;


        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
}
업로드 파일 크기 해결:

#       
spring.servlet.multipart.max-request-size=10MB
#       
spring.servlet.multipart.max-file-size=3MB
swagger 테스트 실행:
在这里插入图片描述
在这里插入图片描述
성공!!
Springboot 통합 아 리 클 라 우 드 OSS 업로드 파일 시스템 튜 토리 얼 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 Springboot 통합 아 리 클 라 우 드 oss 파일 업로드 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 지원 바 랍 니 다!

좋은 웹페이지 즐겨찾기