Integrating Qiniu Cloud Storage in a Spring Boot Application
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_NAMESpring 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);
}
}
}