Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Integrating Qiniu Cloud Storage in a Spring Boot Application

Tech May 13 2

Maven Dependency

Add the Qiniu Java SDK to your project's pom.xml:

<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>7.15.1</version>
</dependency>

Application Configuration

Store your Access Key and Secret Key within application.yml. These credentials can be obtained from the Qiniu Cloud dashboard. Ensure they are kept secure and rotated periodically.

qiniu:
  access-key: YOUR_ACCESS_KEY
  secret-key: YOUR_SECRET_KEY
  bucket: YOUR_BUCKET_NAME

Spring Configuration Class

Initialize the required Qiniu beans by injecting the credentials. The Auth bean handles credential generation, while UploadManager manages file transfers.

@Configuration
public class QiniuStorageConfig {
    @Value("${qiniu.access-key}")
    private String ak;
    @Value("${qiniu.secret-key}")
    private String sk;

    @Bean
    public Auth qiniuAuthProvider() {
        return Auth.create(ak, sk);
    }

    @Bean
    public UploadManager qiniuUploadProvider() {
        Configuration cfg = new Configuration(Region.autoRegion());
        return new UploadManager(cfg);
    }
}

Storage Utility Component

Create a utility component to manage the upload logic. This involves generating an upload token via the Auth instance and executing the file transfer through UploadManager.

@Component
public class CloudStorageHelper {
    private final Auth qiniuAuthProvider;
    private final UploadManager qiniuUploadProvider;
    
    @Value("${qiniu.bucket}")
    private String targetBucket;

    public CloudStorageHelper(Auth qiniuAuthProvider, UploadManager qiniuUploadProvider) {
        this.qiniuAuthProvider = qiniuAuthProvider;
        this.qiniuUploadProvider = qiniuUploadProvider;
    }

    public String persistFile(InputStream dataStream, String objectKey) throws QiniuException {
        String credential = qiniuAuthProvider.uploadToken(targetBucket);
        Response serverResponse = qiniuUploadProvider.put(dataStream, objectKey, credential, null, null);
        return serverResponse.bodyString();
    }
}

REST Endpoint Implementation

Expose a controller endpoint to process incoming multipart file requests and pass the data to the storage utility.

@RestController
@RequestMapping("/api/v1/assets")
public class AssetController {
    private final CloudStorageHelper cloudStorageHelper;

    public AssetController(CloudStorageHelper cloudStorageHelper) {
        this.cloudStorageHelper = cloudStorageHelper;
    }

    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("data") MultipartFile multipartFile) {
        try {
            InputStream fileDataStream = multipartFile.getInputStream();
            String result = cloudStorageHelper.persistFile(fileDataStream, "uploaded_asset");
            return ResponseEntity.ok(result);
        } catch (Exception ex) {
            throw new RuntimeException("File transmission failed", ex);
        }
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.