一、快速入门
快速入门
1、注册账号
2、创建存储空间, 命名xyz对应下面springboot 应用配置bucket
3、创建成功后进入该空间,获取该空间的测试域名,对应下面springboot 应用配置中的path
4、点击“个人面板—密钥管理”,获取 accessKey 和 secretKey
二、pom.xml配置
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>
三、application.properties配置
###七牛存储###
qiniu.AccessKey=Your Access Key
qiniu.SecretKey=Your Secret Key
qiniu.bucket=存储空间名称
qiniu.path=域名
四、Java代码
4.1、七牛服务器配置
package com.example.qiniu2.storage;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 七牛服务器配置
*/
@Data
@Component
public class QiniuProperties {
@Value("${qiniu.AccessKey}")
private String accessKey;
@Value("${qiniu.SecretKey}")
private String secretKey;
@Value("${qiniu.bucket}")
private String bucket;
@Value("${qiniu.path}")
private String path;
}
4.2、七牛文件上传配置器
/**
* 七牛文件上传配置器
*/
@Configuration
public class QiniuUploadConfig {
/**
* 华东机房,配置自己空间所在的区域
*/
@Bean
public com.qiniu.storage.Configuration qiniuConfig() {
return new com.qiniu.storage.Configuration(Zone.zone0());
}
/**
* 构建一个七牛上传工具实例
*
* @param qiniuConfig
* @return
*/
@Bean
public UploadManager uploadManager(com.qiniu.storage.Configuration qiniuConfig) {
return new UploadManager(qiniuConfig);
}
@Bean
public Auth auth(QiniuProperties qiniuProperties) {
return Auth.create(qiniuProperties.getAccessKey(), qiniuProperties.getSecretKey());
}
/**
* 构建七牛空间管理实例
*
* @param auth
* @param qiniuConfig
* @return
*/
@Bean
public BucketManager bucketManager(Auth auth, com.qiniu.storage.Configuration qiniuConfig) {
return new BucketManager(auth, qiniuConfig);
}
@Bean
public Gson gson() {
return new Gson();
}
/**
* 定义七牛云上传的相关策略
*
* @return
*/
@Bean
public StringMap putPolicy() {
StringMap stringMap = new StringMap();
stringMap.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
return stringMap;
}
}
4.4、文件上传
/**
* 文件上传
*/
public interface FileUploadManager {
/**
* 文件上传
*
* @param file
* @return
*/
Response upload(File file);
/**
* 上传文件流
*
* @param inputStream
* @return
*/
Response upload(InputStream inputStream);
/**
* 删除文件
*
* @param key
*/
void delete(String key);
}
@Service
public class FileUploadManagerImpl implements FileUploadManager {
private static final Logger logger = LoggerFactory.getLogger(FileUploadManagerImpl.class);
@Autowired
private QiniuProperties qiniuProperties;
@Autowired
private UploadManager uploadManager;
@Autowired
private BucketManager bucketManager;
@Autowired
private StringMap putPolicy;
@Autowired
private Gson gson;
@Autowired
private Auth auth;
@Override
public Response upload(File file) {
try {
com.qiniu.http.Response response = uploadManager.put(file, null, getUploadToken());
int retry = 0;
while (response.needRetry() && retry < 3) {
response = uploadManager.put(file, null, getUploadToken());
retry++;
}
return getFileUploadResponse(response);
} catch (QiniuException e) {
logger.error("文件上传到七牛服务器出错:", e);
throw new RuntimeException("文件上传到七牛服务器出错:", e);
}
}
@Override
public Response upload(InputStream inputStream) {
try {
com.qiniu.http.Response response = uploadManager.put(inputStream, null, getUploadToken(), null, null);
int retry = 0;
while (response.needRetry() && retry < 3) {
response = uploadManager.put(inputStream, null, getUploadToken(), null, null);
retry++;
}
return getFileUploadResponse(response);
} catch (QiniuException e) {
logger.error("文件上传到七牛服务器出错:", e);
throw new RuntimeException("文件上传到七牛服务器出错:", e);
}
}
@Override
public void delete(String key) {
try {
com.qiniu.http.Response response = bucketManager.delete(qiniuProperties.getBucket(), key);
int retry = 0;
while (response.needRetry() && retry++ < 3) {
response = bucketManager.delete(qiniuProperties.getBucket(), key);
}
} catch (QiniuException e) {
logger.error("删除文件出错:", e);
throw new RuntimeException("删除文件:", e);
}
}
/**
* 获取上传凭证
*
* @return
*/
private String getUploadToken() {
return auth.uploadToken(qiniuProperties.getBucket(), null, 3600, putPolicy);
}
/**
* 获取链接地址
*
* @param response
* @return
* @throws QiniuException
*/
private Response getFileUploadResponse(com.qiniu.http.Response response) throws QiniuException {
DefaultPutRet putRet = gson.fromJson(response.bodyString(), DefaultPutRet.class);
Response fresp = new Response();
fresp.setKey(putRet.key);
fresp.setUrl(qiniuProperties.getPath() + putRet.key);
return fresp;
}
}
4.5、文件上传放回对象
/**
* 文件上传放回对象
*/
@Data
public class Response implements Serializable {
/**
* 键值
*/
private String key;
/**
* 访问URL
*/
private String url;
}
五、测试代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class Qiniu2ApplicationTests {
@Autowired
private FileUploadManager fileUploadManager;
@Test
public void contextLoads() throws Exception {
File file = new File("C:\\Users\\56979\\Desktop\\TIM图片20190924133425.png");
FileInputStream fis = new FileInputStream(file);
Response response = fileUploadManager.upload(fis);
System.out.println(response.getKey());
System.out.println(response.getUrl());
}
}
执行结果:
FoIzafQTcj5vkqDein11RZsmc2zE
http://s.dongni.org/FoIzafQTcj5vkqDein11RZsmc2zE