生活随笔
收集整理的這篇文章主要介紹了
springboot实现简单的文件上传与回显
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前端頁面
input的file類型可以將上傳文件的絕對路徑返回給后臺。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script><link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"><title>Title
</title>
</head>
<body>
<div class="container"><body><div class="col-md-12"><form action="/upload/upload" method="post" enctype="multipart/form-data"><input type="file" name="file" accept="image/*"><br><input type="submit" value="上傳" class="btn btn-success"></form>[[${filename}]]
<br><img th:src="@{${filename}}" alt="圖片"></div></body>
</div>
</body>
</html>
application.properties配置文件
file.upload.path=D://images/
file.upload.path.relative=/images/**
spring.thymeleaf.cache=false
MyWebAppConfigurer配置類
主要配置資源映射,在服務(wù)器輸入路徑時尋找對應(yīng)映射文件。否則直接放在tomcat服務(wù)器中,由于springboot每次啟動都會重啟一個新的tomcat服務(wù)器,文件會丟失,所以放在其他路徑,而通過資源映射則可以訪問tomcat服務(wù)器以外的文件。
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {@Value("${file.upload.path}")private String filePath
;@Value("${file.upload.path.relative}")private String fileRelativePath
;@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry
) {registry
.addResourceHandler(fileRelativePath
).addResourceLocations("file:/" + filePath
);}
}
Controller,
這里注意一個問題,getOriginalFilename在ie瀏覽器中會獲取全部路徑名從而造成io異常,其他瀏覽器正常,解決的話加個瀏覽器判斷就好。
@Controller
@RequestMapping("upload")
public class UploadController {@Value("${file.upload.path}")private String filePath
;@GetMapping("toUpload")public String toUpload(){return "upload";}@RequestMapping("upload")public String upload(@RequestParam("file") MultipartFile file
, Model model
) {String filename
= file
.getOriginalFilename();String path
= filePath
+"Photo/";File filepath
= new File(path
, filename
);if (!filepath
.getParentFile().exists()) {filepath
.getParentFile().mkdirs();}try {file
.transferTo(new File(path
+ File.separator
+ filename
));} catch (IOException e
) {e
.printStackTrace();}model
.addAttribute("filename", "/images/Photo/"+filename
);return "upload";}
}
測試
總結(jié)
以上是生活随笔為你收集整理的springboot实现简单的文件上传与回显的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。