文章插圖

文章插圖
這些天忙著刷題,又怕遺忘了spring boot, 所以抽出一點時間折騰折騰,加深點印象 。
spring boot 的文件上傳與 spring mvc 的文件上傳基本一致,只需注意一些配置即可 。
環境要求: Spring Boot v1.5.1.RELEASE + jdk1.7 + myeclipse
1).引入thymeleaf,支持頁面跳轉
<!– 添加thymeleaf –>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
12345
2).在 src/main/resources 目錄下新建 static 目錄和 templates 目錄 。static存放靜態文件,比如 css、js、image… templates 存放靜態頁面 。先在templates 中新建一個 uploadimg.html
<!DOCTYPE html>
<html>
<head>
【input上傳文件獲取文件名 input上傳文件夾】<title>uploadimg.html</title>
<meta name=”keywords” content=”keyword1,keyword2,keyword3″></meta>
<meta name=”description” content=”this is my page”></meta>
<meta name=”content-type” content=”text/html; charset=UTF-8″></meta>
<!–<link rel=”stylesheet” type=”text/css” href=http://www.mnbkw.com/jxjc/188263/”./styles.css”>–>
</head>
<body>
<form enctype=”multipart/form-data” method=”post” action=”/testuploadimg”>
圖片<input type=”file” name=”file”/>
<input type=”submit” value=http://www.mnbkw.com/jxjc/188263/”上傳”/>
</form>
</body>
</html>
1234567891011121314151617181920
3).在 controller 中寫兩個方法,一個方法跳轉到上傳文件的頁面,一個方法處理上傳文件
//跳轉到上傳文件的頁面
@RequestMapping(value=http://www.mnbkw.com/jxjc/188263/”/gouploadimg”, method = RequestMethod.GET)
public String goUploadImg() {
//跳轉到 templates 目錄下的 uploadimg.html
return “uploadimg”;
}
//處理文件上傳
@RequestMapping(value=http://www.mnbkw.com/jxjc/188263/”/testuploadimg”, method = RequestMethod.POST)
public @ResponseBody String uploadImg(@RequestParam(“file”) MultipartFile file,
HttpServletRequest request) {
String contentType = file.getContentType();
String fileName = file.getOriginalFilename();
/*System.out.println(“fileName–>” + fileName);
System.out.println(“getContentType–>” + contentType);*/
String filePath = request.getSession().getServletContext().getRealPath(“imgupload/”);
try {
FileUtil.uploadFile(file.getBytes(), filePath, fileName);
} catch (Exception e) {
// TODO: handle exception
}
//返回json
return “uploadimg success”;
}
123456789101112131415161718192021222324
4).在上面中,我將文件上傳的實現寫在工具類 FileUtil 的 uploadFile 方法中
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
12345678910
5).在瀏覽器輸入 :http://localhost:8080/gouploadimg 測試
spring.http.multipart.maxFileSize=100Mb
spring.http.multipart.maxRequestSize=100Mb
- wps云文檔里的文件怎么刪除 wps云盤里的文件怎么刪除
- u盤能存超過4g的文件么 u盤怎么存儲4g以上的文件
- win10outlook在哪里打開 win10outlook配置文件在哪里
- windows serve 2008支持的文件系統有哪些? windows 2012 server 安裝
- 如何在虛擬機中打開共享文件 怎么在虛擬機查看共享文件夾
- ftp上傳文件失敗原因 ftp服務器傳輸數據失敗的原因
- 如何編輯json文件 json是什么格式的文件怎么打開
- word怎么保存成pdf文件格式 word怎么保存為PDF格式
- exe文件編輯修改方法 exe程序內容修改
- h5附件上傳 html5文件上傳插件
