SpringBoot-05-之上传文件

mac2022-06-30  100

需要使用引擎模板thymeleaf,如果不清楚,可见04--SpringBoot之模板引擎--thymeleaf

1.新建表单网页:templates/upfile.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form enctype="multipart/form-data" method="post" action="/upload"> 文件上传<input type="file" name="file"/> <input type="submit" value="上传"/> </form> </body> </html>
2.控制器:toly1994.com.toly01.controller.UpFileController
/** * 作者:张风捷特烈 * 时间:2018/5/29:23:15 * 邮箱:1981462002@qq.com * 说明:文件上传控制器 */ @Controller public class UpFileController { @GetMapping("/upload_html") public String uploadHtml() { return "upfile"; } //处理文件上传 @PostMapping(value = "/upload") public @ResponseBody String uploadImg( @RequestParam("file") MultipartFile file, HttpServletRequest request) { if (file.isEmpty()) { return "false"; } String fileName = file.getOriginalFilename();//获取名字 String path = "F:/test"; File dest = new File(path + "/" + fileName); if (!dest.getParentFile().exists()) { //判断文件父目录是否存在 dest.getParentFile().mkdir(); } try { file.transferTo(dest); //保存文件 return "上传成功!"; } catch (IllegalStateException | IOException e) { e.printStackTrace(); return "上传失败!"; } } } 访问下载页:http://localhost:8080/upload_html upload.png

转载于:https://www.cnblogs.com/toly-top/p/9782000.html

最新回复(0)