1先寫一個處理上傳的工具類:html
public class FileUtil {
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();
}
}
2寫一個Form表單
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head >
</head>
<body >
<form enctype="multipart/form-data" method="post" th:action="@{/upload}">
圖片
<input type="file" id="file1" placeholder="請上傳商品圖片" class="form-control" name="product_picture"/>
<input type="submit" value="上傳"/>
</form>
</body>
</html>
3寫一個跳轉到上傳頁面的Controller
@RequestMapping(value="/save")
public String updateproduct(){
return "upload";
}
4寫上傳
@RequestMapping(value="/upload", 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/");
System.out.println("filePath -->" + filePath );
try {
FileUtil.uploadFile(file.getBytes(), filePath, fileName);
} catch (Exception e) {
// TODO: handle exception
}
return "uploadimg success";
}
5在瀏覽器輸入 :http://localhost:8080/save 測試
6展現
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)