若依前后端分離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
英文地址,請注明出處:http://en.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;**接下來會對每一個章節進行詳細…