알리바바 클라우드 OSS에 파일 업로드, 접근 링크 조회 및 삭제 처리

1. Maven 의존성 설정

프로젝트의 pom.xml 파일에 다음 의존성을 추가합니다.

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>2.8.3</version>
</dependency>

2. OSS 연결 설정 파일 구성

oss.properties 파일을 프로젝트 리소스 디렉터리에 생성하고, 아래와 같이 설정합니다.

endpoint=your-oss-endpoint
accessKeyId=your-access-key-id
accessKeySecret=your-access-key-secret
bucketName=your-bucket-name

3. 설정 정보 로드 유틸리티 클래스

설정 파일에서 값을 읽어오는 도구 클래스입니다.

public class OssConfigReader {
    private static final Logger logger = LogManager.getLogger(OssConfigReader.class);

    public static String getProperty(String key) {
        Properties props = new Properties();
        try (InputStream input = OssConfigReader.class.getResourceAsStream("/oss.properties")) {
            if (input == null) {
                logger.error("Resource file oss.properties not found.");
                return null;
            }
            props.load(input);
            String value = props.getProperty(key);
            logger.info("Loaded property: {} = {}", key, value);
            return value;
        } catch (IOException e) {
            logger.error("Failed to load configuration: ", e);
            return null;
        }
    }
}

4. 파일 존재 여부 확인

지정된 객체가 OSS 버킷에 존재하는지 확인하는 메서드입니다.

@Override
public boolean doesObjectExist(String objectKey) {
    String endpoint = OssConfigReader.getProperty("endpoint");
    String accessKeyId = OssConfigReader.getProperty("accessKeyId");
    String accessKeySecret = OssConfigReader.getProperty("accessKeySecret");
    String bucketName = OssConfigReader.getProperty("bucketName");

    OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    try {
        return client.doesObjectExist(bucketName, objectKey);
    } finally {
        client.shutdown();
    }
}

5. 파일 업로드 메서드

업로드된 파일 스트림을 버킷에 저장합니다.

@Override
public void uploadToOss(MultipartFile sourceFile, String remoteKey) {
    String endpoint = OssConfigReader.getProperty("endpoint");
    String accessKeyId = OssConfigReader.getProperty("accessKeyId");
    String accessKeySecret = OssConfigReader.getProperty("accessKeySecret");
    String bucketName = OssConfigReader.getProperty("bucketName");

    OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    try {
        client.putObject(bucketName, remoteKey, sourceFile.getInputStream());
        logger.info("File uploaded successfully: {}", remoteKey);
    } catch (OSSException | ClientException | IOException e) {
        logger.error("Upload failed for file: {}", remoteKey, e);
        throw new RuntimeException("File upload error", e);
    } finally {
        client.shutdown();
    }
}

6. 공유 링크 생성 (임시 접근 URL)

특정 기간 동안 유효한 임시 다운로드 링크를 생성합니다.

@Override
public String generateTemporaryUrl(String objectKey) {
    String endpoint = OssConfigReader.getProperty("endpoint");
    String accessKeyId = OssConfigReader.getProperty("accessKeyId");
    String accessKeySecret = OssConfigReader.getProperty("accessKeySecret");
    String bucketName = OssConfigReader.getProperty("bucketName");

    OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    Date expiration = new Date(System.currentTimeMillis() + 1800000); // 30분 후 만료

    GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectKey, HttpMethod.GET);
    request.setExpiration(expiration);

    URL signedUrl = client.generatePresignedUrl(request);
    client.shutdown();

    return signedUrl.toString();
}

7. 파일 삭제 기능

OSS에서 특정 파일을 제거합니다.

@Override
public void deleteObject(String objectKey) {
    String endpoint = OssConfigReader.getProperty("endpoint");
    String accessKeyId = OssConfigReader.getProperty("accessKeyId");
    String accessKeySecret = OssConfigReader.getProperty("accessKeySecret");
    String bucketName = OssConfigReader.getProperty("bucketName");

    OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    try {
        client.deleteObject(bucketName, objectKey);
        logger.info("Successfully deleted object: {}", objectKey);
    } catch (OSSException e) {
        logger.error("Delete failed for object: {}", objectKey, e);
        throw new RuntimeException("Deletion error", e);
    } finally {
        client.shutdown();
    }
}

8. 컨트롤러에서 파일 처리 요청

HTTP 요청을 통해 파일을 수신하고 비즈니스 로직을 호출합니다.

@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(
        @RequestParam("file") MultipartFile uploadedFile,
        HttpServletRequest request) {

    String fileId = UUID.randomUUID().toString();
    try {
        uploadToOss(uploadedFile, fileId);
        String downloadUrl = generateTemporaryUrl(fileId);
        return ResponseEntity.ok(downloadUrl);
    } catch (Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Upload failed");
    }
}

태그: Alibaba Cloud OSS java Object Storage File Upload Temporary URL

8월 7일 21:39에 게시됨