日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

SpringBoot中通过重写WebMvcConfigurer的方法配置静态资源映射实现图片上传后返回网络Url

發(fā)布時(shí)間:2025/3/19 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot中通过重写WebMvcConfigurer的方法配置静态资源映射实现图片上传后返回网络Url 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

場(chǎng)景

前端調(diào)用上傳照片的功能,將某照片上傳到服務(wù)器上某磁盤(pán)路徑下,然后將通過(guò)靜態(tài)資源映射,將在服務(wù)器上

訪問(wèn)的地址存儲(chǔ)到數(shù)據(jù)庫(kù)中,這樣在需要獲取這種照片的時(shí)候就能通過(guò)服務(wù)器上的url來(lái)獲取和顯示這張照片。

若依前后端分離版本地搭建開(kāi)發(fā)環(huán)境并運(yùn)行項(xiàng)目的教程:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108465662

在此基礎(chǔ)上搭建起來(lái)前后端分離的項(xiàng)目,然后使用若依的通用的上傳接口實(shí)現(xiàn)圖片的上傳。

關(guān)于圖片的上傳的前端以及全流程可以參照:

SpringBoot+El-upload實(shí)現(xiàn)上傳文件到通用上傳接口并返回文件全路徑(若依前后端分離版源碼分析):

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108383134

這里重點(diǎn)講后臺(tái)的配置。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
關(guān)注公眾號(hào)
霸道的程序猿
獲取編程相關(guān)電子書(shū)、教程推送與免費(fèi)下載。

實(shí)現(xiàn)

首先圖片上傳的通用接口,首先新建通用上傳文件的接口

/*** 通用文件上傳下載接口* @author*/ @RestController @RequestMapping("file") @Api(tags = "文件通用上傳下載") public class FileController {@Autowiredprivate FilePathProperties filePathProperties;/*** 上傳文件** @param file* @return*/@PreAuthorize(hasPermi = "system:file:upload")@PostMapping("upload")@ApiOperation("上傳")public AjaxResult uploadFile(@Param("file") MultipartFile file) {AjaxResult ajaxResult = AjaxResult.success();try {// 顯示頭像文件夾路徑String path = filePathProperties.getPath() + "/" + DateUtils.datePath() + "/";FileUtils.check_folder(path);// 上傳后的文件名稱(chēng)String auth_file_name = UploadUtil.save_file(file, path);if (StringUtils.isEmpty(auth_file_name)){return AjaxResult.error(HttpStatus.BAD_REQUEST, "文件格式不合法");}ajaxResult.put("code", 200);ajaxResult.put("message", "成功");ajaxResult.put("fileName", path + auth_file_name);} catch (IOException e) {ajaxResult.put("code", 400);ajaxResult.put("message", "上傳失敗");e.printStackTrace();}return ajaxResult;}/*** 下載文件* @param fileName* @param response* @throws IOException*/@GetMapping("download")@ApiOperation("下載")public void downloadFile(String fileName, HttpServletResponse response) throws IOException {File file = new File(fileName);// 清空responseresponse.reset();// 設(shè)置response的Header 通知瀏覽器 已下載的方式打開(kāi)文件 防止文本圖片預(yù)覽response.addHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes("gbk"), "iso-8859-1")); // 轉(zhuǎn)碼之后下載的文件不會(huì)出現(xiàn)中文亂碼response.addHeader("Content-Length", "" + file.length());// 以流的形式下載文件InputStream fis = new BufferedInputStream(new FileInputStream(fileName));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();OutputStream toClient = new BufferedOutputStream(response.getOutputStream());toClient.write(buffer);toClient.flush();toClient.close();} }

然后這里的filePathProperties是讀取配置文件中配置的文件上傳路徑

?

然后需要在代碼中添加讀取配置文件的配置類(lèi)

/*** 讀取服務(wù)器上傳文件磁盤(pán)路徑*/ @Configuration @RefreshScope @ConfigurationProperties(prefix = "file") public class FilePathProperties {/*** 傳文件磁盤(pán)路徑*/private String path;public String getPath(){return path;}public void setPath(String path){this.path = path;} }

然后前端調(diào)用上傳文件接口,并且將照片上傳到服務(wù)器上指定的路徑下,再調(diào)用保存接口時(shí)將通用上傳接口返回的文件路徑作為保存接口的參數(shù)

?

然后照片就會(huì)上傳到服務(wù)器上指定的路徑

?

然后就是添加靜態(tài)資源映射的配置類(lèi)

package com.ruoyi.fzys.config;import com.ruoyi.common.core.constant.Constants; import com.ruoyi.fzys.config.properties.FilePathProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import java.io.File;/*** 通用配置** @author ruoyi*/ @Configuration public class ResourcesConfig implements WebMvcConfigurer {@Autowiredprivate FilePathProperties filePathProperties;@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry){/** 本地文件上傳路徑 */registry.addResourceHandler(Constants.RESOURCE_PREFIX_DEFINED+"/**").addResourceLocations("file:" + filePathProperties.getPath() + File.separator);}/*** 自定義攔截規(guī)則*/@Overridepublic void addInterceptors(InterceptorRegistry registry){} }

這里實(shí)現(xiàn)WebMvcConfigurer的addResourceHandlers方法

主要是通過(guò)下面實(shí)現(xiàn)靜態(tài)資源映射

registry.addResourceHandler(Constants.RESOURCE_PREFIX_DEFINED+"/**").addResourceLocations("file:" + filePathProperties.getPath() + File.separator);

前面是請(qǐng)求資源的路徑,后面是磁盤(pán)中的實(shí)際路徑。

為了使請(qǐng)求資源的路徑的前綴一致,將其配置得全局常量類(lèi)中

??? /*** 資源映射路徑 前綴? 自定義*/public static final String RESOURCE_PREFIX_DEFINED = "/file";

然后在將圖片路徑保存到數(shù)據(jù)的接口中

??? public AjaxResult add(@RequestBody BusPhotoManagement busPhotoManagement, HttpServletRequest request){String filePath = filePathProperties.getPath();String path=busPhotoManagement.getPhotoPath().substring(filePath.length());//獲取協(xié)議號(hào)String localAddr = request.getLocalAddr();int localPort = request.getLocalPort();String finalURL= Constants.HTTP +localAddr+":"+localPort+Constants.RESOURCE_PREFIX_DEFINED+path;System.out.println("最終路徑 finalURL:"+finalURL);busPhotoManagement.setPhotoPath(finalURL);return toAjax(busPhotoManagementService.insertBusPhotoManagement(busPhotoManagement));}

其中filePathProperties和上面使用的配置文件路徑的一樣

busPhotoManagement.getPhotoPath().substring(filePath.length());就是上面調(diào)用通用上傳接口返回的實(shí)際的磁盤(pán)路徑

Constants.HTTP 是全局常量

??? /*** http請(qǐng)求*/public static final String HTTP = "http://";

然后最終將finalURL存儲(chǔ)到數(shù)據(jù)庫(kù)中就是該照片的網(wǎng)絡(luò)url

能直接在瀏覽器中訪問(wèn)

?

總結(jié)

以上是生活随笔為你收集整理的SpringBoot中通过重写WebMvcConfigurer的方法配置静态资源映射实现图片上传后返回网络Url的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。