javascript
SpringBoot中使用yml配置文件以及配置类实现文件上传下载路径的修改
場(chǎng)景
SpringBoot+thymeleaf實(shí)現(xiàn)文件下載或者實(shí)現(xiàn)文件上傳需要配置文件上傳路徑的地方,
不要寫為固定路徑,在配置文件中指定文件路徑,代碼中直接引用。
避免以后文件路徑修改后需要修改業(yè)務(wù)代碼。
SpringBoot+thymeleaf實(shí)現(xiàn)文件下載參照:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/88786370
實(shí)現(xiàn)
找到SpringBoot項(xiàng)目中的所使用的配置文件application,這里是開(kāi)發(fā)環(huán)境,并且是yml文件。
添加如下自定義配置的值
# 自定義配置 ws:excelTemplateDpwloadPath: C:\release\sites\upload\excel\template注意yml嚴(yán)格的縮進(jìn)格式
注意excelTemplateDpwloadPath: 與C:\release\sites\upload\excel\template要有空格!!!
這里配置的路徑就與要實(shí)現(xiàn)文件下的路徑相對(duì)應(yīng)。
?
新建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中使用時(shí):
@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";// 設(shè)置文件名,根據(jù)業(yè)務(wù)需要替換成要下載的文件名if (fileName != null) {//設(shè)置文件路徑String realPath = configProperties.getExcelTemplateDpwloadPath();//這里使用配置類配置文件路徑File file = new File(realPath , fileName);if (file.exists()) {response.setContentType("application/force-download");// 設(shè)置強(qiáng)制下載不打開(kāi)response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設(shè)置文件名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;} }這樣就可以通過(guò)
String realPath = configProperties.getExcelTemplateDpwloadPath();獲取設(shè)置的文件下載的路徑,以后修改路徑時(shí)直接可以通過(guò)配置文件修改。
總結(jié)
以上是生活随笔為你收集整理的SpringBoot中使用yml配置文件以及配置类实现文件上传下载路径的修改的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java实现向指定URL用POST方法发
- 下一篇: SpringBoot+thymeleaf