Integrating Google Cloud Storage with Spring Boot

Google Cloud Storage (GCS) is a powerful and scalable solution for storing and retrieving large amounts of data. Integrating GCS with Spring Boot allows developers to manage files programmatically within their applications. In this guide, we will walk through setting up GCS with Spring Boot.

Prerequisites

  • Google Cloud Platform (GCP) Account: You’ll need access to a GCP account.
  • GCS Bucket: Create a bucket in your GCP project. Make a note of the bucket name.
  • Service Account: Set up a service account and download the JSON key file for authentication.
  • Spring Boot Project: Ensure you have a working Spring Boot project.


Step 1: Set Up Google Cloud Credentials

  1. Go to the GCP Console.
  2. Navigate to IAM & Admin > Service Accounts.
  3. Create a service account with the necessary permissions (e.g., Storage Admin).
  4. Generate a JSON key file for the service account.
  5. Store the JSON file securely, e.g., in your project’s resources directory or another secure location.

Step 2: Add Dependencies to Your Project

Add the following dependencies to your pom.xml for Maven or build.gradle for Gradle:

Maven

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-storage</artifactId>
    <version>2.27.1</version> <!-- Use the latest version -->
</dependency>        

Step 3: Configure GCP Credentials in Your Application

Environment Variable Method

Set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of the JSON key file:

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/service-account-key.json        

Spring Boot Configuration

Alternatively, you can configure the credentials in the application.properties file:

spring.cloud.gcp.credentials.location=classpath:your-service-account-key.json
spring.cloud.gcp.storage.bucket-name=your-bucket-name        

Step 4: Create a Service Class for GCS Operations

Below is an example service class that interacts with GCS:

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;

@Service
public class GoogleCloudStorageService {

    private final Storage storage;

    public GoogleCloudStorageService() {
        this.storage = StorageOptions.getDefaultInstance().getService();
    }

    public String uploadFile(MultipartFile file, String bucketName) throws IOException {
        BlobId blobId = BlobId.of(bucketName, file.getOriginalFilename());
        BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
        storage.create(blobInfo, file.getBytes());
        return String.format("https://storage.googleapis.com/%s/%s", bucketName, file.getOriginalFilename());
    }

    public byte[] downloadFile(String bucketName, String fileName) {
        Blob blob = storage.get(BlobId.of(bucketName, fileName));
        if (blob == null) {
            throw new IllegalArgumentException("File not found in bucket: " + fileName);
        }
        return blob.getContent();
    }

    public void deleteFile(String bucketName, String fileName) {
        storage.delete(BlobId.of(bucketName, fileName));
    }
}        

Step 5: Create a Controller for File Operations

Below is an example REST controller for handling file uploads, downloads, and deletions:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/files")
public class FileController {

    private final GoogleCloudStorageService storageService;

    @Value("${spring.cloud.gcp.storage.bucket-name}")
    private String bucketName;

    public FileController(GoogleCloudStorageService storageService) {
        this.storageService = storageService;
    }

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String fileUrl = storageService.uploadFile(file, bucketName);
            return ResponseEntity.ok(fileUrl);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("File upload failed: " + e.getMessage());
        }
    }

    @GetMapping("/download/{fileName}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String fileName) {
        byte[] fileContent = storageService.downloadFile(bucketName, fileName);
        return ResponseEntity.ok(fileContent);
    }

    @DeleteMapping("/delete/{fileName}")
    public ResponseEntity<String> deleteFile(@PathVariable String fileName) {
        storageService.deleteFile(bucketName, fileName);
        return ResponseEntity.ok("File deleted successfully.");
    }
}        

Step 6: Test the Integration

  • Upload a File: Use a tool like Postman to send a POST request to /files/upload with a file.
  • Download a File: Access /files/download/{fileName} in a browser or API client.
  • Delete a File: Send a DELETE request to /files/delete/{fileName}.

Conclusion

By following these steps, you can successfully integrate Google Cloud Storage with your Spring Boot application. This setup allows your application to handle file uploads, downloads, and deletions seamlessly, leveraging GCS's scalability and reliability. For further enhancements, consider adding error handling, logging, and securing your endpoints.

Mauro Marins

Senior .NET Software Engineer | Senior Full Stack Developer | C# | .Net Framework | Azure | React | SQL | Microservices

2 个月

Interesting, thanks for sharing!

回复

This message always appears

  • 该图片无替代文字
回复

I have a problem in Google cloud storage caused of billing ..each method refused

回复
Rodrigo Canário

Data Scientist | Machine Learning | Python | Geophysics

2 个月

Very insightful! Keep sharing this knowledge! ??

回复

要查看或添加评论,请登录

JUNIOR N.的更多文章

社区洞察

其他会员也浏览了