当前位置: 首页 > news >正文

springboot实现七牛云的文件上传下载

一:依赖包

		<dependency><groupId>com.qiniu</groupId><artifactId>qiniu-java-sdk</artifactId><qiniu-java-sdk.version>7.7.0</qiniu-java-sdk.version></dependency>

二:具体实现

@RestController
@RequestMapping("/sys/oss/qiniu")
public class OssController {@Autowiredprivate OssQiNiuHelper ossQiNiuHelper;@Value("${jeecg.oss.qiniu.domain}")private String fileDomain;/*** 七牛云文件上传** @param file 文件* @return*/@PostMapping(value = "/upload")public Result<?> upload(MultipartFile file) {if (file == null) {return Result.error("上传文件不能为空");}try {FileInputStream fileInputStream = (FileInputStream) file.getInputStream();String originalFilename = file.getOriginalFilename();String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));String yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());//默认不指定key的情况下,以文件内容的hash值作为文件名String fileKey = UUID.randomUUID().toString().substring(0,16).replace("-", "") + "-" + yyyyMMddHHmmss + fileExtend;Map<String, Object> map = new HashMap<>();DefaultPutRet uploadInfo = ossQiNiuHelper.upload(fileInputStream, fileKey);map.put("fileName", uploadInfo.key);map.put("name", originalFilename);map.put("size", file.getSize());//七牛云文件私有下载地址(看自己七牛云公开还是私有配置)map.put("url", "http://" + fileDomain + "/" + uploadInfo.key);return Result.ok(map);} catch (Exception e) {e.printStackTrace();return Result.error(e.getMessage());}}/*** 七牛云私有文件下载** @param filename 文件名* @return*/@GetMapping(value = "/private/file/{filename}")public void privateDownload(@PathVariable("filename") String filename, HttpServletResponse response) {if (filename.isEmpty()) {return;}try {String privateFile = ossQiNiuHelper.getPrivateFile(filename);response.sendRedirect(privateFile);} catch (Exception e) {e.printStackTrace();}}/*** 七牛云文件下载** @param filename 文件名* @return*/@RequestMapping(value = "/file/{filename}", method = {RequestMethod.GET})public void download(@PathVariable("filename") String filename, HttpServletResponse response) {if (filename.isEmpty()) {return;}try {String privateFile = ossQiNiuHelper.getFile(filename);response.sendRedirect("http://" + privateFile);} catch (Exception e) {e.printStackTrace();}}/*** 七牛云文件下载** @param filename 文件名* @return*/@RequestMapping(value = "/file/delete/{filename}", method = {RequestMethod.GET})public Result<?> delete(@PathVariable("filename") String filename, HttpServletResponse response) {if (filename.isEmpty()) {return Result.error("文件不能为空");}try {boolean delete = ossQiNiuHelper.delete(filename);} catch (Exception e) {e.printStackTrace();}return Result.ok("文件删除成功");}
}

三:配置类

@Configuration
public class QiNiuConfig {@Value(value = "${jeecg.oss.qiniu.accessKey}")private String accessKey;@Value(value = "${jeecg.oss.qiniu.secretKey}")private String secretKey;@Value(value = "${jeecg.oss.qiniu.zone}")private String zone;/*** 初始化配置*/@Beanpublic com.qiniu.storage.Configuration ossConfig() {System.out.println(zone);switch (zone) {case "huadong":return new com.qiniu.storage.Configuration(Region.huadong());case "huabei":return new com.qiniu.storage.Configuration(Region.huabei());case "huanan":return new com.qiniu.storage.Configuration(Region.huanan());case "beimei":return new com.qiniu.storage.Configuration(Region.beimei());default:throw new RuntimeException("存储区域配置错误");}}/*** 认证信息实例** @return*/@Beanpublic Auth auth() {return Auth.create(accessKey, secretKey);}/*** 构建一个七牛上传工具实例*/@Beanpublic UploadManager uploadManager(com.qiniu.storage.Configuration configuration) {return new UploadManager(configuration);}/*** 构建七牛空间管理实例** @param auth          认证信息* @param configuration com.qiniu.storage.Configuration* @return*/@Beanpublic BucketManager bucketManager(Auth auth, com.qiniu.storage.Configuration configuration) {return new BucketManager(auth, configuration);}/*** Gson** @return*/@Beanpublic Gson gson() {return new Gson();}
}

@Component
public class OssQiNiuHelper {@Value("${jeecg.oss.qiniu.bucketName}")private String bucketName;@Value("${jeecg.oss.qiniu.domain}")private String fileDomain;@Autowiredprivate Configuration configuration;@Autowiredprivate UploadManager uploadManager;@Autowiredprivate BucketManager bucketManager;// 密钥配置@Autowiredprivate Auth auth;@Autowiredprivate Gson gson;//简单上传模式的凭证public String getUpToken() {return auth.uploadToken(bucketName);}//覆盖上传模式的凭证public String getUpToken(String fileKey) {return auth.uploadToken(bucketName, fileKey);}/*** 上传二进制数据** @param data* @param fileKey* @return* @throws IOException*/public DefaultPutRet upload(byte[] data, String fileKey) throws IOException {Response res = uploadManager.put(data, fileKey, getUpToken(fileKey));// 解析上传成功的结果DefaultPutRet putRet = gson.fromJson(res.bodyString(), DefaultPutRet.class);System.out.println(putRet.key);System.out.println(putRet.hash);return putRet;}/*** 上传输入流** @param inputStream* @param fileKey* @return* @throws IOException*/public DefaultPutRet upload(InputStream inputStream, String fileKey) throws IOException {Response res = uploadManager.put(inputStream, fileKey, getUpToken(fileKey), null, null);// 解析上传成功的结果DefaultPutRet putRet = gson.fromJson(res.bodyString(), DefaultPutRet.class);System.out.println(putRet.key);System.out.println(putRet.hash);return putRet;}/*** 删除文件** @param fileKey* @return* @throws QiniuException*/public boolean delete(String fileKey) throws QiniuException {Response response = bucketManager.delete(bucketName, fileKey);return response.statusCode == 200 ? true : false;}/*** 获取公共空间文件** @param fileKey* @return*/public String getFile(String fileKey) throws Exception {String encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");String url = String.format("%s/%s", fileDomain, encodedFileName);return url;}/*** 获取私有空间文件** @param fileKey* @return*/public String getPrivateFile(String fileKey) throws Exception {String encodedFileName = URLEncoder.encode(fileKey, "utf-8").replace("+", "%20");String publicUrl = String.format("%s/%s", "http://" + fileDomain, encodedFileName);long expireInSeconds = 3600;//1小时,可以自定义链接过期时间String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);return finalUrl;}}

四:注意点

4.1.域名备案

使用七牛云的使用必须得备案域名,并且做dns解析,才能用七牛云的加速域名,七牛云默认是有几种解析方式的这里推荐使用dns解析,还有一种文件解析是比较麻烦的不推荐

4.2配置七牛云域名,一般是使用二级域名即可

配置完了二级域名去对应的域名提供服务商解析下记录即可生效

http://www.lryc.cn/news/333945.html

相关文章:

  • 【RISC-V 指令集】RISC-V 向量V扩展指令集介绍(六)- 向量内存一致性模型
  • Lvgl9 WindowsSimulator Visual Studio2017
  • 【STL】链表(list)
  • node.js常用指令
  • Flutter第六弹 基础列表ListView
  • 【考研经验贴】24考研860软件工程佛系上岸经验分享【丰富简历、初复试攻略、导师志愿、资料汇总】
  • 15-1-Flex布局
  • 深入浅出 -- 系统架构之负载均衡Nginx的性能优化
  • AI大模型下的策略模式与模板方法模式对比解析
  • 前端| 富文本显示不全的解决方法
  • 数据结构——链表
  • uniapp使用vuex
  • C++从入门到精通——this指针
  • Hive3.0.0建库表命令测试
  • 一起学习python——基础篇(7)
  • 【LeetCode热题100】74. 搜索二维矩阵(二分)
  • Android OkHttp
  • Java常用API_正则表达式_字符串的替换和截取方法——小练习
  • 从头开发一个RISC-V的操作系统(四)嵌入式开发介绍
  • Web漏洞-文件上传常见验证
  • 如何在 Node.js 中使用 bcrypt 对密码进行哈希处理
  • 嵌入式学习49-单片机2
  • 汽车EDI:如何与奔驰建立EDI连接?
  • 性能分析--内存知识
  • 目标检测标签分配策略,难样本挖掘策略
  • Java | Leetcode Java题解之第16题最接近的三数之和
  • FIN和RST的区别,几种TCP连接出现RST的情况
  • 2024/4/1—力扣—删除字符使频率相同
  • Spring源码解析-容器基本实现
  • Python 基于 OpenCV 视觉图像处理实战 之 OpenCV 简单视频处理实战案例 之四 简单视频倒放效果