前端
图片上传.html
<html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>图片上传</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> <form id="uploadForm" enctype="multipart/form-data" th:action="@{/toAdd}" method="post" th:onsubmit="return toSubmit()"> <!--这里注意:【return】【onsubmit的位置在form标签】--> <input accept="image/*" type="file" name="file" v-model="pic" /> <br> <input type="submit" name="提交"> </form>
<script> function toSubmit() { var form = document.getElementById("uploadForm"); let formData = new FormData(form); if (formData.get("img").size > 1024 * 1024) { alert("图片过大,请提交图片截屏或者选择小于1M的图片!"); return false; } else { return true; } } </script> </body> </html>
后端:
LoginController.java
@Controller public class LoginController { @RequestMapping("/upload12") public String upload12() { return "图片上传"; //就是返回以上的html的名字 } @ResponseBody @PostMapping("/upload") public String upload2(@RequestParam("file") MultipartFile file) { String fileName = file.getOriginalFilename(); String filePath = "/Users/mac/Desktop/未命名文件夹"; if (file.isEmpty()) { return "文件为空!"; } try { uploadFile(file.getBytes(), filePath, getUUID()); } catch (Exception e) { e.printStackTrace(); } return "上传成功!"; // 前后端分离,则返回json } // 写入文件,filepath是文件路径【tomcat默认的文件上传大小是1M,如果想要修改,需要添加配置文件】 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 + ".png"); out.write(file); out.flush(); out.close(); } // 同时需要将上传图片的原始文件名和存储文件名、以及关联id存入一个数据表中【这里省略】。 // 生成uuid public static String getUUID() { UUID uuid = UUID.randomUUID(); String str = uuid.toString(); String uuidStr = str.replace("-", ""); return uuidStr; } }
标签:return,String,filePath,用户,file,上传,public,springboot From: https://www.cnblogs.com/cjin-01/p/16721577.html