springboot单文件上传(可看缩略图)

1先写一个处理上传的工具类:

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 >
<script language="javascript">
$(function(){
$("#file1").on("change",function(){
var file=this.files[0];
if(this.files && file){
var reader=new FileReader();
reader.onload=function(e){
$("#img1").attr("src",e.target.result);
}
reader.readAsDataURL(file);
}
});
});
</script>
</head>
<body >
<form enctype="multipart/form-data" method="post" th:action="@{/upload}">
图片
<input type="file" id="file1" placeholder="请上传商品图片" class="form-control" name="product_picture"/>
//显示上传图片缩略图《写js》
<img id="img1" src="" style="width:200px;height:160px;">
<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展示

 

猜你喜欢

转载自www.cnblogs.com/lr12339/p/9300596.html