SpringBoot集成七牛云OSS详细介绍
Spring Boot 集成七牛云 OSS 主要涉及配置和使用 com.qiniu.storage.Configuration
、com.qiniu.storage.Region
、com.qiniu.util.Auth
等类。以下是一个基本的集成示例:
- 添加 Maven 依赖:
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[最新版本]</version>
</dependency>
- 配置 application.properties:
# 七牛云配置
qiniu.access-key=你的AccessKey
qiniu.secret-key=你的SecretKey
qiniu.bucket=你的存储空间名称
qiniu.base-url=http://图片服务器域名
- 创建配置类:
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class QiniuConfig {
@Value("${qiniu.access-key}")
private String accessKey;
@Value("${qiniu.secret-key}")
private String secretKey;
@Value("${qiniu.bucket}")
private String bucket;
@Value("${qiniu.base-url}")
private String baseUrl;
@Bean
public Configuration configuration() {
return new Configuration(Region.region2());
}
// ... 其他需要的Bean
}
- 创建服务类:
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Service
public class QiniuService {
@Autowired
private UploadManager uploadManager;
@Autowired
private Auth auth;
@Value("${qiniu.bucket}")
private String bucket;
@Value("${qiniu.base-url}")
private String baseUrl;
public String upload(MultipartFile file) throws IOException {
final String token = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(file.getInputStream(), null, token, null, null);
// 解析
评论已关闭