准备工作
1.创建一个七牛云账号
2.登录账号,进入个人中心,创建一组密钥(ak和sk)
3. 创建一个公有的存储空间(桶)
注:存储地区的选择基于你的用户的分布主要在哪里。
七牛云直接白送10GB给我们玩,很适合做项目想白嫖的小伙伴。
实战演练
Java SDK_SDK 下载_对象存储 - 七牛开发者中心(这里的代码仅供参考)
1.springboot项目中导入必要的依赖
<!-- 七牛云-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.13.0, 7.13.99]</version>
</dependency>
<!-- gson,上传文件时要用-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
<scope>compile</scope>
</dependency>
<!-- @ConfigurationProperties注解爆红-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2.yml文件中填入ak,sk和桶的相关配置
qiniu:
accessKey: z3214mq2xG5w7-KHQk7oBiJC6sbjrjmlVNai0sai
secretKey: _wys_Vf2RWpZqG9Hnlq32lQ17wvULnHeJSIjnGez
bucket: gmgx2024
prefixUrl: http://siz0shti6.jl-cnm.clouddn.com/
prefixUrl在这
3.写一个QiniuConfig来接收这些配置
@ConfigurationProperties(prefix = "qiniu")
@Data
@Component
public class QiniuConfig {
private String accessKey;
private String secretKey;
private String bucket;
private String prefixUrl;
}
4.编写上传文件的核心代码
为什么只有上传?因为这个桶是公有的,只需要上传时把返回的url存到数据库中,要下载文件时输入url即可下载。(最后介绍私有桶的上传和下载)
控制器
@Tag(name="文件控制器",description = "基于七牛云实现文件上传和下载")
@RestController
@RequestMapping("file")
public class FileController {
@Autowired
private FileService fileService;
@Operation(summary = "uploadFile",description = "基于七牛云上传文件")
@PostMapping("/uploadFile")
public Result uploadFile(MultipartFile file){
String url = fileService.upload(file);
if(url!=null){
return new Result(Code.UPLOAD_SUCCESS,"文件上传成功",url);
}
return new Result(Code.UPLOAD_FAIL,"文件上传失败",null);
}
}
服务类
package com.example.qiniufileupload.service.impl;
import com.example.qiniufileupload.config.QiniuConfig;
import com.example.qiniufileupload.service.FileService;
import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
@Service
public class FileServiceImpl implements FileService {
@Autowired
private QiniuConfig qiniuConfig;
/**
*
* @param file 要上传到七牛云的文件
* @return url 上传后的文件的完整url
*/
public String upload(MultipartFile file) {
try {
// 获取文件的名字 aaa.jpg
String originalFilename = file.getOriginalFilename();
//file扩展名 extendFileName jpg
String extendFileName = originalFilename.substring(originalFilename.lastIndexOf("."));
// 默认不指定key的情况下,以文件内容的hash值作为文件名 时间日期前缀
LocalDate currentDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd/");
// todo:构建新的文件名 2024/8/29/一个uuid.jpg
String key = currentDate.format(formatter) + UUID.randomUUID().toString().replace("-", "") + extendFileName;
// 构造一个带指定 Region 对象的配置类
Configuration zone = new Configuration(Zone.huanan());//我们刚开始选的是华南地区
// 从 MultipartFile 直接获取输入流,避免先保存到本地再上传
InputStream inputStream = file.getInputStream();
//创建Auth对象,填写ak和sk
Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
//获得上传凭证
String upToken = auth.uploadToken(qiniuConfig.getBucket());
System.out.println(upToken);
//z3214mq2xG5w7-KHQk7oBiJC6zojrjmlVNcn0sai:oHRCCHPiB2YlJxxCYtDyVOb3lCs=:eyJzY29wZSI6ImdtZ3gyMDI0IiwiZGVhZGxpbmUiOjE3MjQ5Mjc2NjN9
//隐藏了判空条件
try (InputStream ignored = inputStream)
{
UploadManager uploadManager = new UploadManager(zone);//指定zone
//上传图片到七牛云
Response response = uploadManager.put(inputStream, key, upToken,null,null);
/**
* 用gson将浏览器响应的body字符串解析成DefaultPutRet的实例化对象
* ↓
* public final class DefaultPutRet {
* public String hash;
* public String key;//在七牛云存储空间中的名字
*
* public DefaultPutRet() {
* }
* }
*
*/
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
String url = "";
url = qiniuConfig.getPrefixUrl() + putRet.key;
return url;
} catch (IOException ex) {
return null;
}
} catch (Exception e) {
return null;
}
}
}
5.用knife4j测试一下
首先随便找一张图片(bushi)
在knife4j的界面中选择这个文件并上传
拿到返回的url地址
在七牛云中我们保存的文件夹中看到了我们刚上传的图片
使用情景
做需要上传文件的相关业务时,我们可以把上传成功后文件的url保存到数据库中,在需要时直接查数据库获取文件的url,在前端做对应的回显即可。
*************************************************************************
私有桶的上传和下载
1.创建一个私有桶
2.修改相关配置
3.编写上传和下载的核心代码
控制器
@Tag(name="文件控制器",description = "基于七牛云实现文件上传和下载")
@RestController
@RequestMapping("file")
public class FileController {
@Autowired
private FileService fileService;
@Operation(summary = "uploadFile",description = "基于七牛云上传文件")
@PostMapping("/uploadFile")
public Result uploadFile(MultipartFile file){
String url = fileService.upload(file);
if(url!=null){
return new Result(Code.UPLOAD_SUCCESS,"文件上传成功",url);
}
return new Result(Code.UPLOAD_FAIL,"文件上传失败",null);
}
@Operation(summary = "downloadFile",description = "基于七牛云下载文件")
@PostMapping("/downloadFile/{fileName}")
public Result downloadFile(@PathVariable String fileName){
String url = fileService.download(fileName);
if(url!=null){
return new Result(Code.DOWNLOAD_SUCCESS,"文件下载成功",url);
}
return new Result(Code.DOWNLOAD_FAIL,"文件下载失败",null);
}
}
服务类
@Service
public class FileServiceImpl implements FileService {
@Autowired
private QiniuConfig qiniuConfig;
/**
*
* @param file 要上传到七牛云的文件
* @return url 上传后的文件的完整url
*/
public String upload(MultipartFile file) {
try {
// 获取文件的名字 aaa.jpg
String originalFilename = file.getOriginalFilename();
//file扩展名 extendFileName jpg
String extendFileName = originalFilename.substring(originalFilename.lastIndexOf("."));
String key = UUID.randomUUID().toString().replace("-", "") + extendFileName;
// 构造一个带指定 Region 对象的配置类
Configuration zone = new Configuration(Zone.huanan());//我们刚开始选的是华南地区
// 从 MultipartFile 直接获取输入流,避免先保存到本地再上传
InputStream inputStream = file.getInputStream();
//创建Auth对象,填写ak和sk
Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
//获得上传凭证
String upToken = auth.uploadToken(qiniuConfig.getBucket());
System.out.println(upToken);
//z3214mq2xG5w7-KHQk7oBiJC6zojrjmlVNcn0sai:oHRCCHPiB2YlJxxCYtDyVOb3lCs=:eyJzY29wZSI6ImdtZ3gyMDI0IiwiZGVhZGxpbmUiOjE3MjQ5Mjc2NjN9
//隐藏了判空条件
try (InputStream ignored = inputStream)
{
UploadManager uploadManager = new UploadManager(zone);//指定zone
//上传图片到七牛云
Response response = uploadManager.put(inputStream, key, upToken,null,null);
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
String url = "";
url = qiniuConfig.getPrefixUrl() + putRet.key;
return url;
} catch (IOException ex) {
return null;
}
} catch (Exception e) {
return null;
}
}
@Override
public String download(String fileName) {
String urlString = "";
try {
// domain 下载 domain, eg: qiniu.com【必须】
// useHttps 是否使用 https【必须】
// key 下载资源在七牛云存储的 key【必须】
String domain = qiniuConfig.getPrefixUrl();
//todo 需要修改domain
DownloadUrl url = new DownloadUrl(domain, qiniuConfig.getUseHttps(), fileName);
// 带有效期
long expireInSeconds = 60;
long deadline = System.currentTimeMillis() / 1000 + expireInSeconds;
Auth auth = Auth.create(qiniuConfig.getAccessKey(), qiniuConfig.getSecretKey());
urlString = url.buildURL(auth, deadline);
System.out.println(urlString);
} catch (Exception e) {
e.printStackTrace();
}
return urlString;
}
}
4.测试
注意这里的url的格式,带上了过期时间和token