springboot整合七牛云oss操作文件
文章目录
- springboot整合七牛云oss操作文件
- 核心代码(记得修改application.yml配置参数⭐)
- maven依赖
- QiniuOssProperties配置类
- UploadController
- ResponseResult统一封装响应结果
- ResponseType响应类型枚举
- OssUploadService接口
- QiniuOssUploadServiceImpl实现类
- QiniuOssApplication启动类
- application.yml
- 文件/图片上传(数据流方式上传)⭐
- 获取accessKey和secretKey配置内容
- 创建一个存储空间和获取bucket(存储空间名称)、服务器域名
- 文件删除⭐
springboot整合七牛云oss操作文件
核心代码(记得修改application.yml配置参数⭐)
maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>qiniuOss</artifactId><version>1.0-SNAPSHOT</version><properties><!-- springboot版本--><spring-boot.version>2.7.2</spring-boot.version><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><!--实现自定义的properties(@ConfigurationProperties注解下的内容)可以在application.yml出现提示。导入了这个依赖,当我们运行项目后就会在target目录下面自动生成/META-INF/spring-configuration-metadata.json文件--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><!-- springboot-web--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- String工具类包 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version></dependency><!-- lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency>
<!-- 七牛云oss sdk--><dependency><groupId>com.qiniu</groupId><artifactId>qiniu-java-sdk</artifactId><version>[7.7.0, 7.10.99]</version></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.5</version><scope>compile</scope></dependency></dependencies></project>
QiniuOssProperties配置类
package com.boot.config;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;/*** 七牛云oss配置类* @author youzhengjie 2022-10-07 18:07:19*/
@Component
@Data
@ConfigurationProperties(prefix = "qiniu")
@EnableConfigurationProperties({QiniuOssProperties.class
})
public class QiniuOssProperties {/*** 下面的AK、SK都要从七牛云的密钥管理中获取*/private String accessKey;private String secretKey;/*** 指定存储空间名称*/private String bucket;/*** 七牛云图片服务器域名(有效期30天,过期可以重新创建新的存储空间)*/private String ossUrl;
}
UploadController
package com.boot.controller;import com.boot.data.ResponseResult;
import com.boot.service.OssUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;/*** @author youzhengjie 2022-10-07 18:08:18*/
@RestController
public class UploadController {@Autowired@Qualifier("qiniuOssUploadServiceImpl") //指定spring注入的实现类为七牛云oss实现类private OssUploadService ossUploadService;/*** 图片上传* @param imageFile* @return*/@PostMapping(path = "/imageUpload")public ResponseResult imageUpload(MultipartFile imageFile){return ossUploadService.imageUpload(imageFile);}/*** 文件删除* @return*/@DeleteMapping(path = "/fileDelete")public ResponseResult fileDelete(String fileFullName){return ossUploadService.fileDelete(fileFullName);}}
ResponseResult统一封装响应结果
package com.boot.data;import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;/*** 统一响应结果*/
@JsonInclude(JsonInclude.Include.NON_NULL) //为null的字段不进行序列化
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResponseResult<T> {/*** 响应状态码*/private Integer code;/*** 响应状态码对应的信息提示*/private String msg;/*** 返回给前端的数据*/private T data;public ResponseResult(Integer code, String msg) {this.code = code;this.msg = msg;}public ResponseResult(Integer code, T data) {this.code = code;this.data = data;}}
ResponseType响应类型枚举
package com.boot.enums;/*** 响应类型枚举类* @author youzhengjie 2022-09-22 22:47:21*/
public enum ResponseType {/*** 响应类型*/IMAGE_UPLOAD_SUCCESS(901,"图片上传成功"),IMAGE_UPLOAD_ERROR(902,"图片上传失败"),FILE_FORMAT_UNSUPPORT(903,"不支持该文件格式,上传失败"),FILE_DELETE_SUCCESS(904,"文件删除成功"),FILE_DELETE_ERROR(905,"文件删除失败"),;private int code;private String message;ResponseType(int code, String message) {this.code = code;this.message = message;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}
}
OssUploadService接口
package com.boot.service;import com.boot.data.ResponseResult;
import com.boot.enums.ResponseType;
import org.springframework.web.multipart.MultipartFile;/*** oss上传service接口* @author youzhengjie 2022-10-06 23:13:28*/
public interface OssUploadService {/*** oss图片上传* @param imageFile* @return 上传结果*/ResponseResult imageUpload(MultipartFile imageFile);/*** oss文件删除* @param fileFullName 文件全名,也就是下面这个代码生成的名字(记住不要加上域名),例如:* String newFileName = new StringBuilder()* .append(fileDir)* .append(uuidFileName)* .append(fileSuffix).toString();** @return 删除结果*/ResponseResult fileDelete(String fileFullName);}
QiniuOssUploadServiceImpl实现类
package com.boot.service.impl;import com.boot.config.QiniuOssProperties;
import com.boot.data.ResponseResult;
import com.boot.enums.ResponseType;
import com.boot.service.OssUploadService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;/*** 七牛云oss文件上传实现类* @author youzhengjie 2022-10-06 23:14:17*/
@Service("qiniuOssUploadServiceImpl")
@Slf4j
public class QiniuOssUploadServiceImpl implements OssUploadService {@Autowiredprivate QiniuOssProperties qiniuOssProperties;/*** 检查文件是否是图片类型* @param originalFilename* @return true代表是图片,false则不是图片*/private boolean isImage(String originalFilename){//将文件名全部变小写String lowerOriginalFilename = originalFilename.toLowerCase();return lowerOriginalFilename.endsWith(".jpg") ||lowerOriginalFilename.endsWith(".png") ||lowerOriginalFilename.endsWith(".jpeg");}@Overridepublic ResponseResult imageUpload(MultipartFile imageFile) {//获取上传前的文件原名String oldFileName = imageFile.getOriginalFilename();//封装响应结果ResponseResult<Object> result = new ResponseResult<>();//如果不是图片则直接返回if(!isImage(oldFileName)){result.setCode(ResponseType.FILE_FORMAT_UNSUPPORT.getCode());result.setMsg(ResponseType.FILE_FORMAT_UNSUPPORT.getMessage());return result;}//构造一个带指定自动的Region对象的配置类Configuration cfg = new Configuration(Region.autoRegion());cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本UploadManager uploadManager = new UploadManager(cfg);//以日期作为目录,每一天的图片都会放到不同的目录下,方便管理SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");String fileDir = simpleDateFormat.format(new Date());//UUID文件名String uuidFileName = UUID.randomUUID().toString().replaceAll("-", "");//获取文件后缀名 .jpgString fileSuffix= oldFileName.substring(oldFileName.lastIndexOf("."));//上传到oss中的新的图片文件名String newFileName = new StringBuilder().append(fileDir).append(uuidFileName).append(fileSuffix).toString();try {//获取前端传来的文件流InputStream inputStream = imageFile.getInputStream();Auth auth = Auth.create(qiniuOssProperties.getAccessKey(), qiniuOssProperties.getSecretKey());String upToken = auth.uploadToken(qiniuOssProperties.getBucket());//七牛云oss上传文件的核心方法Response response = uploadManager.put(inputStream,newFileName,upToken,null, null);result.setCode(ResponseType.IMAGE_UPLOAD_SUCCESS.getCode());result.setMsg(ResponseType.IMAGE_UPLOAD_SUCCESS.getMessage());//返回一个外面可以访问的图片地址。拼接域名+新的图片全路径,这样我们通过这个路径就可以直接在外面访问图片了result.setData(qiniuOssProperties.getOssUrl()+newFileName);return result;}catch (Exception e){e.printStackTrace();result.setCode(ResponseType.IMAGE_UPLOAD_ERROR.getCode());result.setMsg(ResponseType.IMAGE_UPLOAD_ERROR.getMessage());return result;}}/*** 七牛云oss文件删除* @param fileFullName 文件全名,也就是下面这个代码生成的名字(记住不要加上域名):* String newFileName = new StringBuilder()* .append(fileDir)* .append(uuidFileName)* .append(fileSuffix).toString();* @return 删除结果*/@Overridepublic ResponseResult fileDelete(String fileFullName) {//封装响应结果ResponseResult<Object> result = new ResponseResult<>();//构造一个带指定 Region 对象的配置类Configuration cfg = new Configuration(Region.autoRegion());Auth auth = Auth.create(qiniuOssProperties.getAccessKey(), qiniuOssProperties.getSecretKey());BucketManager bucketManager = new BucketManager(auth, cfg);try {//七牛云oss文件删除核心方法Response response = bucketManager.delete(qiniuOssProperties.getBucket(), fileFullName);result.setCode(ResponseType.FILE_DELETE_SUCCESS.getCode());result.setMsg(ResponseType.FILE_DELETE_SUCCESS.getMessage());return result;} catch (QiniuException ex) {ex.printStackTrace();result.setCode(ResponseType.FILE_DELETE_ERROR.getCode());result.setMsg(ResponseType.FILE_DELETE_ERROR.getMessage());return result;}}
}
QiniuOssApplication启动类
package com.boot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class QiniuOssApplication {public static void main(String[] args) {SpringApplication.run(QiniuOssApplication.class,args);}}
application.yml
server:port: 8231
spring:servlet:#文件上传配置multipart:max-file-size: 3MBmax-request-size: 6MB#七牛云oss配置
qiniu:# 密钥管理的AKaccessKey: xPu-62ptMpg-kolm4nPVcvWgUnK1EZgu27ffKpBE#密钥管理的SKsecretKey: gDxkqTu7i7BBgbsvoQ7h4bmE5m16aRyHXyQ1Zc6D#指定我们文件上传的存储空间名称bucket: java-qiniu# 七牛云图片服务器域名(有效期30天,过期可以重新创建新的存储空间)ossUrl: http://rjc4vwz0g.hn-bkt.clouddn.com/
文件/图片上传(数据流方式上传)⭐
获取accessKey和secretKey配置内容
- 登录七牛云并进入下面的网址:
七牛云网址
创建一个存储空间和获取bucket(存储空间名称)、服务器域名
- 1:进入七牛云控制面板:
七牛云网址
- 2:创建新的存储空间:
- 3:查看刚刚创建的存储空间:
- 4:获取我们的存储空间域名
- 5:上传操作。由于我们后端进行了特殊校验,只允许传入图片,下面演示:
文件删除⭐
- 1:获取文件的key:
- 2:文件删除:
相关文章:

springboot整合七牛云oss操作文件
文章目录 springboot整合七牛云oss操作文件核心代码(记得修改application.yml配置参数⭐)maven依赖QiniuOssProperties配置类UploadControllerResponseResult统一封装响应结果ResponseType响应类型枚举OssUploadService接口QiniuOssUploadServiceImpl实现…...

跨国传输的常见问题与对应解决方案
在今天的全球化时代,跨国数据传输已经成为一个不可或缺的需求。不论是个人还是企业,都需要通过网络将文件或数据从一个国家传输到另一个国家,以实现信息共享、协作、备份等目的。然而,跨国数据传输并不是一项容易的任务࿰…...

Git(七).git 文件夹瘦身,GitLab 永久删除文件
目录 一、问题背景二、问题复现2.1 新建项目2.2 上传大文件2.3 上传结果 三、解决方案3.1 GitLab备份与还原1)备份2)还原 3.2 删除方式一:git filter-repo 命令【推荐】1)安装2)删除本地仓库文件3)重新关联…...

多线程锁的升级原理是什么
在 Java 中,锁共有 4 种状态,级别从低到高依次为:无状态锁,偏向锁,轻量级锁和重量级锁状态,这几个状态会随着竞争情况逐渐升级。锁可以升级但不能降级。 多线程锁锁升级过程 如下图所示 多线程锁的升级过程…...

金山文档轻维表之删除所有行记录
目前脚本文档里面的只有删除行记录功能,但是需要指定ID值,不能实现批量删除,很多人反馈但是官方无回应,挺奇怪的 但是批量删除的需求我很需要,最后研究了一下,还是挺容易实现的 测试: 附上脚本…...
站坑站坑站坑站坑站坑
站坑站坑站坑站坑站坑站坑站坑...
在Vue中,你可以使用动态import()语法来动态加载组件
在Vue中,你可以使用动态import()语法来动态加载组件。动态导入允许你在需要时异步加载组件,这样可以提高应用程序的初始加载性能。 下面是一个使用动态导入加载组件的示例: <template> <div> <button click"loadComp…...
金蝶云星空表单插件获取日期控件判空处理(代码示例)
文章目录 金蝶云星空表单插件获取日期控件判空处理C#实现 金蝶云星空表单插件获取日期控件判空处理 C#实现 DateTime? deliveryDate (DateTime?)this.View.Model.GetValue("FApproveDate");//审核日期long leadtime 20;//天数if (!deliveryDate.IsNullOrEmpty()…...

通过xshell传输文件到服务器
一、user is not in the sudoers file. This incident will be reported. 参考链接: [已解决]user is not in the sudoers file. This incident will be reported.(简单不容易出错的方式)-CSDN博客 简单解释下就是: 0、你的root需要设置好密码 sudo …...
centos7.9编译安装python3.7.2
联网环境下编译安装python3.7.2,不联网则需要配置cnetos7.9离线源 下载解压软件包 [rootlocalhost ~]# tar -xf Python-3.7.3.tar.gz [rootlocalhost ~]# ls anaconda-ks.cfg Python-3.7.3 Python-3.7.3.tar.gz [rootlocalhost ~]# [rootlocalhost ~]# cd Pytho…...

【教3妹学编程-算法题】2913. 子数组不同元素数目的平方和 I
-----------------第二天------------------------ 面试官 : 好的, 我们再来做个算法题吧。平时工作中会尝试用算法吗, 用到了什么数据结构? 3妹 : 有用到, 用到了 bla bla… 面试官 : 好的, 题目是这样的࿱…...
是否会有 GPT-5 的发布?
本心、输入输出、结果 文章目录 是否会有 GPT-5 的发布?前言围绕 GPT-5 的信息OpenAI 期待增长GPT-5 - 到底是真的在训练,还是一个虚构的故事Sam Altman字里行间包含的信息我们在什么时候可以期待 GPT-5 的发布GPT-5 预计将在哪些方向努力GPT-5 在听觉领域GPT-5 在视频处理领…...
使用 Selenium Python 检查元素是否存在
像 Selenium 这样的自动化工具使我们能够通过不同的语言和浏览器自动化 Web 流程并测试应用程序。 Python 是它支持的众多语言之一,并且是一种非常简单的语言。 它的Python客户端帮助我们通过Selenium工具与浏览器连接。 Web 测试对于开发 Web 应用程序至关重要&am…...

const迭代器与模板构造函数
在自己实现C中list的时候,当实现const迭代器的时候,发现报错了,一直思考到现在 才发现是一个,很简单的问题,但是也让我有了一点感受,我在这里给大家分享一下。文章目录 1.当时遇到的问题2.解决方法3. 自己的…...

在Qt中解决opencv的putText函数无法绘制中文的一种解决方法
文章目录 1.问题2.查阅资料3.解决办法 1.问题 在opencv中,假如直接使用putText绘制中文,会在图像上出现问号,如下图所示: 2.查阅资料 查了一些资料,说想要解决这个问题,需要用到freetype库或者用opencv…...

【Linux】第六站:Centos系统如何安装软件?
文章目录 1.Linux安装软件的方式2.Linux的软件生态3. yum4. rzsz软件的安装与卸载5.yum如何知道去哪里下载软件? 1.Linux安装软件的方式 在linux中安装软件常用的有三种方式 源代码安装(我们还需要进行编译运行后才可以,很麻烦) …...

Istio 实战
文章目录 Istio流量管理分享会【1】什么是istio?【2】istio 可以干什么?【3】业务中的痛点?【4】istio 高级流量管理5.1 istio 组件介绍与原理5.2 sidercar何时注入?如何控制是否注入?5.3 查看sidecar 容器插入的容器中的iptablesDestination RuleVirtual ServiceGateways…...

【Midjourney入门教程4】与AI对话,写好prompt的必会方法
文章目录 1、语法2、单词3、要学习prompt 框架4、善用参数(注意版本)5、善用模版6、临摹7、垫图 木匠不会因为电动工具的出现而被淘汰,反而善用工具的木匠,收入更高了。 想要驾驭好Midjourney,可以从以下方面出发调整&…...

基于单片机的智能灭火小车设计
欢迎大家点赞、收藏、关注、评论啦 ,由于篇幅有限,只展示了部分核心代码。 技术交流认准下方 CSDN 官方提供的联系方式 文章目录 概要 一、整体设计方案1.1 整体设计任务1.2 整体设计要求1.3 系统整体方案设计1.3.1 整体模块设计1.3.2 整体设计方案选择…...

[Machine Learning][Part 7]神经网络的基本组成结构
这里我们将探索神经元/单元和层的内部工作原理。特别是,与之前学习的回归/线性模型和逻辑模型进行比较。最后接介绍tensorflow以及如何利用tensorflow来实现这些模型。 神经网络和大脑的神经元工作原理类似,但是比大脑的工作原理要简单的多。大脑中神经元的工作原理…...

学校招生小程序源码介绍
基于ThinkPHPFastAdminUniApp开发的学校招生小程序源码,专为学校招生场景量身打造,功能实用且操作便捷。 从技术架构来看,ThinkPHP提供稳定可靠的后台服务,FastAdmin加速开发流程,UniApp则保障小程序在多端有良好的兼…...

ardupilot 开发环境eclipse 中import 缺少C++
目录 文章目录 目录摘要1.修复过程摘要 本节主要解决ardupilot 开发环境eclipse 中import 缺少C++,无法导入ardupilot代码,会引起查看不方便的问题。如下图所示 1.修复过程 0.安装ubuntu 软件中自带的eclipse 1.打开eclipse—Help—install new software 2.在 Work with中…...

c#开发AI模型对话
AI模型 前面已经介绍了一般AI模型本地部署,直接调用现成的模型数据。这里主要讲述讲接口集成到我们自己的程序中使用方式。 微软提供了ML.NET来开发和使用AI模型,但是目前国内可能使用不多,至少实践例子很少看见。开发训练模型就不介绍了&am…...

JUC笔记(上)-复习 涉及死锁 volatile synchronized CAS 原子操作
一、上下文切换 即使单核CPU也可以进行多线程执行代码,CPU会给每个线程分配CPU时间片来实现这个机制。时间片非常短,所以CPU会不断地切换线程执行,从而让我们感觉多个线程是同时执行的。时间片一般是十几毫秒(ms)。通过时间片分配算法执行。…...
css3笔记 (1) 自用
outline: none 用于移除元素获得焦点时默认的轮廓线 broder:0 用于移除边框 font-size:0 用于设置字体不显示 list-style: none 消除<li> 标签默认样式 margin: xx auto 版心居中 width:100% 通栏 vertical-align 作用于行内元素 / 表格单元格ÿ…...
Android Bitmap治理全解析:从加载优化到泄漏防控的全生命周期管理
引言 Bitmap(位图)是Android应用内存占用的“头号杀手”。一张1080P(1920x1080)的图片以ARGB_8888格式加载时,内存占用高达8MB(192010804字节)。据统计,超过60%的应用OOM崩溃与Bitm…...
大语言模型(LLM)中的KV缓存压缩与动态稀疏注意力机制设计
随着大语言模型(LLM)参数规模的增长,推理阶段的内存占用和计算复杂度成为核心挑战。传统注意力机制的计算复杂度随序列长度呈二次方增长,而KV缓存的内存消耗可能高达数十GB(例如Llama2-7B处理100K token时需50GB内存&a…...

九天毕昇深度学习平台 | 如何安装库?
pip install 库名 -i https://pypi.tuna.tsinghua.edu.cn/simple --user 举个例子: 报错 ModuleNotFoundError: No module named torch 那么我需要安装 torch pip install torch -i https://pypi.tuna.tsinghua.edu.cn/simple --user pip install 库名&#x…...
React---day11
14.4 react-redux第三方库 提供connect、thunk之类的函数 以获取一个banner数据为例子 store: 我们在使用异步的时候理应是要使用中间件的,但是configureStore 已经自动集成了 redux-thunk,注意action里面要返回函数 import { configureS…...

Rust 开发环境搭建
环境搭建 1、开发工具RustRover 或者vs code 2、Cygwin64 安装 https://cygwin.com/install.html 在工具终端执行: rustup toolchain install stable-x86_64-pc-windows-gnu rustup default stable-x86_64-pc-windows-gnu 2、Hello World fn main() { println…...