Spring Boot配置七牛云(Kotlin版)

746 阅读2分钟

由于新的业务框架已经换成了Spring Boot。

关于七牛云的配置网上很多都是Java的版本,故有此文。

配置文件

# 下面需要换成你的包名,记得修改这里仅以demo做示例
package com.demo.configuration

import com.google.gson.Gson
import com.qiniu.common.Region
import com.qiniu.storage.BucketManager
import com.qiniu.storage.UploadManager
import com.qiniu.util.Auth
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

/**
 * @author watson
 * @date 2021/5/21 9:16 上午
 */

@Configuration
class QiniuCloudConfiguration {
    @Value("\${qiniu.accessKey}")
    private val accessKey: String? = null

    @Value("\${qiniu.secretKey}")
    private val secretKey: String? = null

    @Value("\${qiniu.bucket}")
    private val bucket: String? = null

    @Value("\${qiniu.zone}")
    private val zone: String? = null


    /***
     * 配置对应的存储地区
     * 由于Zone的弃用,我们这里选用Region的模式
     */
    @Bean
    fun config(): com.qiniu.storage.Configuration {
        return when (zone) {
           "huadong" -> {
                com.qiniu.storage.Configuration(Region.huadong())
            }
            "huabei" -> {
                com.qiniu.storage.Configuration(Region.huabei())
            }
            "huanan" -> {
                com.qiniu.storage.Configuration(Region.huanan())
            }
            "beimei" -> {
                com.qiniu.storage.Configuration(Region.beimei())
            }
            else -> throw Exception("七牛云区域配置错误")
        }
    }

    /***
     * 获取一个上传工具实例
     */
    @Bean
    fun uploadManager(): UploadManager {
        return UploadManager(config())
    }

    /**
     * 认证信息实例
     */
    @Bean
    fun auth(): Auth {
        return Auth.create(accessKey, secretKey)
    }

    /***
     * 上传空间实例
     */

    @Bean
    fun bucketManager(): BucketManager {
        return BucketManager(auth(), config())
    }

    @Bean
    fun gson(): Gson {
        return Gson()
    }
}

Spring Boot Service文件

package com.demo.service

import com.qiniu.common.QiniuException
import com.qiniu.http.Response
import com.qiniu.storage.BucketManager
import com.qiniu.storage.UploadManager
import com.qiniu.util.Auth
import com.qiniu.util.StringMap
import org.springframework.beans.factory.InitializingBean
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import java.io.File
import java.io.InputStream
import kotlin.jvm.Throws


interface IQiniuCloudService {
    @Throws(QiniuException::class)
    fun uploadFile(file: File, filename: String): String

    @Throws(QiniuException::class)
    fun uploadFileStream(inputStream: InputStream, filename: String): String

    @Throws(QiniuException::class)
    fun remove(key: String): String
}


@Service
class QiniuCloudService : IQiniuCloudService, InitializingBean {
    @Autowired
    lateinit var uploaderManager: UploadManager

    @Autowired
    lateinit var bucketManager: BucketManager

    @Autowired
    lateinit var auth: Auth

    @Value("\${qiniu.bucket}")
    lateinit var bucket: String

    @Value("\${qiniu.domain}")
    lateinit var domain: String

    lateinit var putPolicy: StringMap

    override fun uploadFile(file: File, filename: String): String {
        var response: Response? = uploaderManager.put(file, filename, getUploadToken())
        var retry = 0
        while (response?.needRetry() == true && retry < 3) {
            response = uploaderManager.put(file, filename, getUploadToken());
            retry++
        }
        while (response?.statusCode == 200) {
            return "https://$domain/$filename"
        }
        return "上传失败"
    }

    override fun uploadFileStream(inputStream: InputStream, filename: String): String {
        var response: Response = uploaderManager.put(inputStream, filename, getUploadToken(), null, null)
        var retry = 0
        while (response.needRetry() && retry < 3) {
            response = uploaderManager.put(inputStream, filename, getUploadToken(), null, null);
            retry++
        }
        return if (response.statusCode == 200) "https://$domain/$filename" else "上传失败"
    }

    override fun remove(key: String): String {
        var response: Response = bucketManager.delete(bucket, key)
        var retry = 0
        while (response.needRetry() && retry < 3) {
            response = bucketManager.delete(bucket, key)
            retry++
        }
        return if (response.statusCode == 200) "删除成功" else "删除失败"
    }

    override fun afterPropertiesSet() {
        putPolicy = StringMap()
        putPolicy.put(
            "returnBody",
            "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":\${imageInfo.height}}"
        )
    }

    // 获取上传凭证
    fun getUploadToken(): String? {
        return auth.uploadToken(bucket, null, 3600, putPolicy)
    }
}

Spring Boot测试文件

package com.wdc.service

import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import java.io.File

/**
 * @author watson haw
 * @date 2021/5/21 11:45 上午
 */

@SpringBootTest
class QiniuCloudTests {
    @Autowired
    lateinit var qiniuCloudService: IQiniuCloudService

    @Test
    fun testUpload() {
        val ret: String = qiniuCloudService.uploadFile(
            File("测试文件路径"),
            "测试文件名.测试文件后缀"
        )
        println("访问地址$ret")
    }

    @Test
    fun testRemove() {
        val ret: String = qiniuCloudService.remove(
            "hello.jpeg"
        )
        println("操作结果$ret")
    }
}

Spring Boot的application.yml配置文件

qiniu:
  zone: "七牛云区域"
  domain: "七牛云域名"
  bucket: "七牛云bucket"
  accessKey: "七牛云key"
  secretKey: "七牛云秘钥"

这里配置文件需要系统环境变量中读取,勿硬编码到配置文件里

原Java链接在此,适配了Kotlin的版本供大家参考

SpringBoot(24) 整合七牛云实现文件上传