美文网首页
Spring Boot文件上传

Spring Boot文件上传

作者: 索伦x | 来源:发表于2019-02-25 00:10 被阅读0次

    POM.xml

        <!-- 添加thymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    

    上传页面

    resource目录下新建templates,创建文件uploadimg.html

    
    <!DOCTYPE html>
    <html>
      <head>
        <title>uploadimg.html</title>
     
        <meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
        <meta name="description" content="this is my page"></meta>
        <meta name="content-type" content="text/html; charset=UTF-8"></meta>
     
        <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
     
      </head>
     
      <body>
      <form enctype="multipart/form-data" method="post" action="/testuploadimg">
        图片<input type="file" name="file"/>
        <input type="submit" value="上传"/>
        </form>
      </body>
    </html>
    

    上传Controller

    @Controller
    @Api(value = "/test", tags = "文件上传")  //swagger分类标题注解
    public class UploadController {
    
    
        //跳转到上传文件的页面
        @RequestMapping(value="/gouploadimg", method = RequestMethod.GET)
        public String goUploadImg() {
            //跳转到 templates 目录下的 uploadimg.html
            return "uploadimg";
        }
    
        //处理文件上传
        @RequestMapping(value="/testuploadimg", 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/");
            try {
                FileUtil.uploadFile(file.getBytes(), filePath, fileName);
            } catch (Exception e) {
                // TODO: handle exception
            }
            //返回json
            return "uploadimg success";
        }
    }
    

    上传工具类FileUtil.java

    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();
        }
    }
    

    测试

    在浏览器中输入http://localhost:8080/testuploadimg

    相关文章

      网友评论

          本文标题:Spring Boot文件上传

          本文链接:https://www.haomeiwen.com/subject/fdiiyqtx.html