若依前后端分离Vue3版本接入阿里云OSS

一、引入依赖

首先在commom 模块的pom 下面引入 阿里云OSS 的 依赖

        <!--     阿里云oss     --><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.17.4</version></dependency>

二、安装x-file-store

一行代码将文件存储到本地、FTP、SFTP、WebDAV、阿里云 OSS、华为云 OBS、七牛云 等各个厂商。

<dependency><groupId>org.dromara.x-file-storage</groupId><artifactId>x-file-storage-spring</artifactId><version>2.3.0</version>
</dependency>

三、applacation.yml 添加相关配置

记得将  access-key 换成自己的

dromara:x-file-storage: #文件存储配置default-platform: aliyun-oss-1 #默认使用的存储平台thumbnail-suffix: ".min.jpg" #缩略图后缀,例如【.min.jpg】【.png】#对应平台的配置写在这里,注意缩进要对齐aliyun-oss:- platform: aliyun-oss-1 # 存储平台标识enable-storage: true  # 启用存储access-key: ??secret-key: ??end-point: ??bucket-name: ??domain: ?? # 访问域名,注意“/”结尾,例如:https://abc.oss-cn-shanghai.aliyuncs.com/base-path: test/ # 基础路径

然后再启动类上方添加    @EnableFileStorage 注解

@EnableFileStorage
@SpringBootApplication
public class SpringFileStorageTestApplication {public static void main(String[] args) {SpringApplication.run(SpringFileStorageTestApplication.class,args);}}

四、后端改造 

需要改造 admin模块下的  controller/common/CommonController.java

建议直接新项目直接复制代码使用

package com.soft.web.controller.common;import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.soft.common.config.RuoYiConfig;
import com.soft.common.constant.Constants;
import com.soft.common.core.domain.AjaxResult;
import com.soft.common.utils.StringUtils;
import com.soft.common.utils.file.FileUploadUtils;
import com.soft.common.utils.file.FileUtils;
import com.soft.framework.config.ServerConfig;/*** 通用请求处理* * @author ruoyi*/
@RestController
@RequestMapping("/common")
public class CommonController
{private static final Logger log = LoggerFactory.getLogger(CommonController.class);@Autowiredprivate ServerConfig serverConfig;@Autowiredprivate FileStorageService fileStorageService;//注入实列private static final String FILE_DELIMETER = ",";/*** 通用下载请求* * @param fileName 文件名称* @param delete 是否删除*/@GetMapping("/download")public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request){try{if (!FileUtils.checkAllowDownload(fileName)){throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));}String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);String filePath = RuoYiConfig.getDownloadPath() + fileName;response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);FileUtils.setAttachmentResponseHeader(response, realFileName);FileUtils.writeBytes(filePath, response.getOutputStream());if (delete){FileUtils.deleteFile(filePath);}}catch (Exception e){log.error("下载文件失败", e);}}/*** 通用上传请求(单个)*/@PostMapping("/upload")public AjaxResult uploadFile(MultipartFile file) throws Exception{try{//            // 上传文件路径
//            String filePath = RuoYiConfig.getUploadPath();
//            // 上传并返回新文件名称
//            String fileName = FileUploadUtils.upload(filePath, file);
//            String url = serverConfig.getUrl() + fileName;// 上传文件,返回信息FileInfo fileInfo = fileStorageService.of(file).upload();String fileName = fileInfo.getFilename();AjaxResult ajax = AjaxResult.success();ajax.put("url", fileInfo.getUrl());ajax.put("fileName", fileName);ajax.put("newFileName", FileUtils.getName(fileName));ajax.put("originalFilename", file.getOriginalFilename());return ajax;}catch (Exception e){return AjaxResult.error(e.getMessage());}}/*** 通用上传请求(多个)*/@PostMapping("/uploads")public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception{try{// 上传文件路径String filePath = RuoYiConfig.getUploadPath();List<String> urls = new ArrayList<String>();List<String> fileNames = new ArrayList<String>();List<String> newFileNames = new ArrayList<String>();List<String> originalFilenames = new ArrayList<String>();for (MultipartFile file : files){// 上传并返回新文件名称String fileName = FileUploadUtils.upload(filePath, file);String url = serverConfig.getUrl() + fileName;urls.add(url);fileNames.add(fileName);newFileNames.add(FileUtils.getName(fileName));originalFilenames.add(file.getOriginalFilename());}AjaxResult ajax = AjaxResult.success();ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));return ajax;}catch (Exception e){return AjaxResult.error(e.getMessage());}}/*** 本地资源通用下载*/@GetMapping("/download/resource")public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)throws Exception{try{if (!FileUtils.checkAllowDownload(resource)){throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));}// 本地资源路径String localPath = RuoYiConfig.getProfile();// 数据库资源地址String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);// 下载名称String downloadName = StringUtils.substringAfterLast(downloadPath, "/");response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);FileUtils.setAttachmentResponseHeader(response, downloadName);FileUtils.writeBytes(downloadPath, response.getOutputStream());}catch (Exception e){log.error("下载文件失败", e);}}
}

五、前端改造

1.改造 ImagePreview 组件

/src/components/ImagePreview/index.vue

改造 realSrc 的计算属性

const realSrc = computed(() => {if (!props.src) {return;}let real_src = props.src.split(",")[0];if (isExternal(real_src)) {return real_src;}if(real_src.includes("http")){return real_src;}return import.meta.env.VITE_APP_BASE_API + real_src;
});

2. 改造ImageUpload 组件

/src/components/ImageUpload/index.vue

修改监听器

watch(() => props.modelValue, val => {if (val) {// 首先将值转为数组const list = Array.isArray(val) ? val : props.modelValue.split(",");// 然后将数组转为对象数组fileList.value = list.map(item => {if (typeof item === "string") {if(item.includes('http')){item = { name: item, url: item };return item}if (item.indexOf(baseUrl) === -1) {item = { name: baseUrl + item, url: baseUrl + item };} else {item = { name: item, url: item };}}return item;});} else {fileList.value = [];return [];}
},{ deep: true, immediate: true });

最后整个整个项目的改造接入就完成啦

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/news/914258.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/914258.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2025年微软mos备考攻略-穷鬼版

说实话&#xff0c;微软MOS认证是微软官芳推出的办公软件方面的认证&#xff0c;考试难度真的不大&#xff0c;完全没必要报班&#xff0c;自学完全OK&#xff01;一、25 年报考MOS认证详情报名时间&#xff1a;随时可以在官网或ji构报名&#xff08;ji构报名会送备考资料&…

数据库版本自动管理

FlywayDB 是一款 开源数据库版本管理工具&#xff0c;开发中将表结构的变更或数据初始化脚本维护好&#xff0c;更新到测试环境或线上发版启动服务的时候&#xff0c;会检测版本号自动执行数据库变更&#xff0c;可以减少每次发版到其他环境的人工执行操作。 工作流程初始化阶段…

解决Linux绑定失败地址已使用(端口被占用)的问题

文章目录解决 bind failed: Address already in use 问题一、问题原因1. **端口已经被其他程序占用**2. **端口处于 TIME_WAIT 状态**3. **未正确关闭套接字**二、如何排查和解决问题1. **确认端口是否被占用**2. **查找并杀掉占用端口的进程**3. **等待端口释放&#xff08;TI…

Ragas的Prompt Object

Prompt在Ragas中被用在各种指标、合成数据生成任务中。同时也为提供了替换各种自动以提示词的方式。Ragas提供了如下几种Prompt Objects。 instruction:prompt的基础组成,通过自然语言清晰的描述LLM需要完成的任务。在prompt object中用instruction变量定义。few-shot exampl…

PHP语法高级篇(一):日期时间处理和包含文件

从本篇文章开始&#xff0c;将学习PHP的高级特性内容。本篇文章将记录在PHP中如何进行日期时间处理和包含文件的学习过程。 一、日期和时间 在PHP中&#xff0c;date() 函数用于格式化日期或时间。 说明 date(string $format, ?int $timestamp null): string 使用指定整数…

请求服务端获取broker的机房归属信息异常

该错误表明服务在尝试获取 broker 的 ​机房归属信息​ 时遇到异常。以下是详细分析和解决方案建议&#xff1a;​问题定位与常见原因​​网络问题​客户端无法连接存储机房信息的元数据服务​&#xff08;如配置中心、注册中心&#xff09;。防火墙或安全组阻断了相关端口&…

Android 中的多线程编程全面解析

Android 中的多线程编程全面解析 一、Android 线程模型基础 主线程&#xff08;UI 线程&#xff09;特性 唯一性&#xff1a;每个应用只有一个主线程职责&#xff1a;处理 UI 操作和用户交互限制&#xff1a;禁止在主线程执行耗时操作&#xff08;超过5秒会导致 ANR&#xff09…

golang -gorm 增删改查操作,事务操作

增删改查 1. 插入数据// api func SaveUser(ctx *gin.Context) {result : &common.Result{}user : &dao.User{}err : ctx.ShouldBindJSON(&user)if err ! nil {ctx.JSON(http.StatusOK, result.Fail(400, "请使用json数据格式传值"))return}// 调用验证函…

大数据时代UI前端的智能化服务升级:基于用户情境的主动服务设计

hello宝子们...我们是艾斯视觉擅长ui设计、前端开发、数字孪生、大数据、三维建模、三维动画10年经验!希望我的分享能帮助到您!如需帮助可以评论关注私信我们一起探讨!致敬感谢感恩!一、引言&#xff1a;从 “被动响应” 到 “主动预判” 的 UI 服务革命当用户在暴雨天打开外卖…

CUDA性能优化实战:7个步骤让并行归约算法提升10倍效率

本文深入探讨了一个经典的并行计算算法——并行归约&#xff08;Parallel Reduction&#xff09;的性能优化过程&#xff0c;通过七个渐进式的优化步骤&#xff0c;展示了如何将算法性能提升至极致。这项研究基于Mark Harris在NVIDIA网络研讨会中提出的优化方法&#xff0c;在重…

详解梯度消失和梯度爆炸(反向传播)?

什么是梯度消失&#xff1f;梯度消失&#xff08;Gradient Vanishing&#xff09; 是指在训练神经网络时&#xff0c;反向传播过程中计算得到的梯度&#xff08;用于更新参数的重要信息&#xff09;随着网络层数的增加而急剧减小&#xff0c;甚至趋近于零的现象。这会导致深层网…

端到端自动驾驶:挑战与前沿

端到端自动驾驶&#xff1a;挑战与前沿 End-to-End Autonomous Driving: Challenges and Frontiers 自动驾驶研究社区已见证了越来越多采用端到端算法框架的方法的快速增长&#xff0c;这些方法利用原始传感器输入生成车辆的运动规划&#xff0c;而不是专注于诸如检测和运动预测…

rust cargo 编译双架构的库

这个错误表明你的 Rust 工具链没有安装 aarch64-apple-darwin 目标平台。以下是完整的解决方案&#xff1a; 解决方案 ​​安装目标平台​​ (必须步骤) rustup target add aarch64-apple-darwin​​验证安装​​ (可选但推荐) rustup target list --installed # 应该能看到 aa…

Apache Shiro 框架详解

文章目录一、Shiro 核心功能二、Shiro 架构2.1 三层架构2.2 核心组件&#xff08;SecurityManager 内部&#xff09;三、核心流程详解3.1 认证流程&#xff08;登录&#xff09;流程步骤&#xff1a;认证流程序列图&#xff1a;3.2 授权流程&#xff08;权限校验&#xff09;流…

【保姆级喂饭教程】Windows下安装Git Flow

目录前言一、SourceTree二、Git for Windows (previously MSysGit)1. 下载补丁1.1 getopt.exe1.2 libintl3.dll1.3 libiconv2.dll1.4 安装补丁2. 安装Git Flow3. 测试3.1 初始化&#xff08;Initialize&#xff09;3.2 设置远程3.3 创建分支3.4 功能开发3.5 功能提交3.6 推送分…

manifest.json只有源码视图没其他配置

项目场景&#xff1a;提示&#xff1a;这里简述项目相关背景&#xff1a;有时候我们从git上面拉下代码&#xff0c;第一次运行时发现&#xff0c;没运行项&#xff0c;再看manifest.json文件&#xff0c;就只有json文件&#xff0c;没有其他配置项原因分析&#xff1a;提示&…

数据分析-名词

一、网页访问数据指标1.IP &#xff08;Internet Protocol&#xff09;独立IP 通常采用独立IP数&#xff0c; 理论上指00:00-24:00内相同IP地址重复访问只被计算一次。而不同的商业统计工具&#xff0c;缩短去 掉重复统计的时间&#xff0c;也是数据统计放大的一个常用套路。 &…

UDP属于是一种什么服务器?

UDP是一种传输层协议&#xff0c;通常会被应用在计算机网络中&#xff0c;为企业与用户提供无连接的数据信息传输功能&#xff0c;与TCP协议相比较来说&#xff0c;UDP会更加的简单但是UDP在可靠性方面没有一定的保证&#xff0c;属于是一种基于UDP协议进行通信的服务器。UDP服…

ARM单片机OTA解析(一)

文章目录一、单片机烧写程序的几种方法二、Bootloader如何加载启动App一、单片机烧写程序的几种方法 在线应用编程&#xff0c;由开发者实现Bootloader功能&#xff0c;比如ARM单片机的Code分区中的Flash本是存储用户应用程序的区间(上电从此处执行用户代码)&#xff0c;开发者…

C语言基础教程--从入门到精通

C语言基础教程–从入门到精通&#xff08;总体概括&#xff09; 接下来会对每一个章节进行详细的总结与整理&#xff0c;希望对大家有用&#xff01;大家一起学习&#xff01; 目录C语言基础教程--从入门到精通&#xff08;总体概括&#xff09;**接下来会对每一个章节进行详细…