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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

SpringBoot中使用yml配置文件以及配置类实现文件上传下载路径的修改

發布時間:2025/3/19 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot中使用yml配置文件以及配置类实现文件上传下载路径的修改 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

場景

SpringBoot+thymeleaf實現文件下載或者實現文件上傳需要配置文件上傳路徑的地方,

不要寫為固定路徑,在配置文件中指定文件路徑,代碼中直接引用。

避免以后文件路徑修改后需要修改業務代碼。

SpringBoot+thymeleaf實現文件下載參照:

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

實現

找到SpringBoot項目中的所使用的配置文件application,這里是開發環境,并且是yml文件。

添加如下自定義配置的值

# 自定義配置 ws:excelTemplateDpwloadPath: C:\release\sites\upload\excel\template

注意yml嚴格的縮進格式

注意excelTemplateDpwloadPath: 與C:\release\sites\upload\excel\template要有空格!!!

這里配置的路徑就與要實現文件下的路徑相對應。

?

新建config包并在config包下新建ConfigProperties.java

package com.ws.bus.config;import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component;/*** @author badado* @version 1.0* @see**/ @Component @ConfigurationProperties(prefix = ConfigProperties.PREFIX) public class ConfigProperties {public static? final String PREFIX = "ws";private String excelTemplateDpwloadPath;public String getExcelTemplateDpwloadPath() {return excelTemplateDpwloadPath;}public void setExcelTemplateDpwloadPath(String excelTemplateDpwloadPath) {this.excelTemplateDpwloadPath = excelTemplateDpwloadPath;}}

聲明所使用的文件路徑的屬性名,并生成set和get方法。

在具體要使用的Controller中使用時:

@Controller @RequestMapping("/wmsReceiveOrder") @EnableConfigurationProperties(ConfigProperties.class) public class WmsReceiveOrderController {@Autowiredprivate ConfigProperties configProperties;@Description("模板下載")@RequestMapping("/downloadOnlineLearnMaterials")public String downloadFile(HttpServletRequest request, HttpServletResponse response) {String fileName = "template.xlsx";// 設置文件名,根據業務需要替換成要下載的文件名if (fileName != null) {//設置文件路徑String realPath = configProperties.getExcelTemplateDpwloadPath();//這里使用配置類配置文件路徑File file = new File(realPath , fileName);if (file.exists()) {response.setContentType("application/force-download");// 設置強制下載不打開response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設置文件名byte[] buffer = new byte[1024];FileInputStream fis = null;BufferedInputStream bis = null;try {fis = new FileInputStream(file);bis = new BufferedInputStream(fis);OutputStream os = response.getOutputStream();int i = bis.read(buffer);while (i != -1) {os.write(buffer, 0, i);i = bis.read(buffer);}System.out.println("success");} catch (Exception e) {e.printStackTrace();} finally {if (bis != null) {try {bis.close();} catch (IOException e) {e.printStackTrace();}}if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}}return null;} }

這樣就可以通過

String realPath = configProperties.getExcelTemplateDpwloadPath();

獲取設置的文件下載的路徑,以后修改路徑時直接可以通過配置文件修改。

總結

以上是生活随笔為你收集整理的SpringBoot中使用yml配置文件以及配置类实现文件上传下载路径的修改的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。