springboot上传图片
-
新建一个springboot项目;
-
在java/main/com/ljx 创建一个controller.fileController类
内容如下:
package com.ljx.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.websocket.server.PathParam; import java.io.File; import java.io.IOException; import java.util.UUID; /** * @author 李捷禧 * Date: 2022/12/13 * ClassName: fileController */ @Controller public class fileController { @GetMapping(value = "/file") public String file() { return "/file"; } @PostMapping(value = "/fileUpload") public String fileUpload(@RequestParam(value = "file") MultipartFile file, Model model, HttpServletRequest request) { if (file.isEmpty()) { System.out.println("文件不能为空!"); } // 文件名 String fileName = file.getOriginalFilename(); //后缀名,在文件名后面加“." String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 上传后的路径,自己设定要跟后面获取图片位置一样 String filePath = "E://work//image//"; // 新文件名 fileName = UUID.randomUUID() + suffixName; //判断文件夹里面是否存在 File dest = new File(filePath + fileName); //不存在就新建一个图片文件 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } //将文件存到新建文件的位置去 try { file.transferTo(dest); } catch (IOException e) { e.printStackTrace(); } //对应上面的文件路径 String filename = "/work/image/" + fileName; model.addAttribute("filename", filename); return "/file"; } }
-
在com/ljx/config一个配置类
内容如下:
package com.ljx.config; /** * @author 李捷禧 * Date: 2022/12/13 * ClassName: MyWebAppConfigurer */ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 资源映射路径 */ @Configuration public class MyWebAppConfigurer implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/work/image/**").addResourceLocations("file:E:/work/image/"); } }
-
在application.properties文件加一下配置:
spring.mvc.view.prefix=/WEB-INF/ spring.mvc.view.suffix=.jsp
-
在webapp/WEB-INF创建一个file.jsp
内容如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="/fileUpload" method="post" enctype="multipart/form-data"> <label>上传图片</label> <input type="file" name="file"/> <input type="submit" value="上传"/> </form> <p>图片:</p> <img src="${filename}"/> </body> </html>
!注意:在此之前,需要项目配置好 jsp可运行环境,见以往博客园
运行结果是:
标签:web,springboot,springframework,fileName,file,org,import,上传,图片 From: https://www.cnblogs.com/jessi200/p/16979687.html