springboot2.x文件图片上传
原创 justdoit 发表于:2018-10-30 14:23:57
  阅读 :374   收藏   编辑

大小限制配置

Spring boot2.x,一次请求默认单个文件最大为1MB,全部文件最大为10MB,可在配置文件配置大小

spring.servlet.multipart.max-file-size=50MB
spring.servlet.multipart.max-request-size=50MB

配置jsp

#jsp 支持
spring.mvc.view.suffix=.jsp
spring.mvc.view.prefix=/WEB-INF/ui/
#静态资源
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static

为了方便访问WEB-INF下的页面,可配置UrlFilenameViewController,参考:https://faceghost.com/article/327181 

创建页面

在WEB-INF/ui下创建upload.jsp

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title> servlet 文件上传</title>
</head>
<body>
<form action="execUpload" method="post" enctype="multipart/form-data">
    fileName:<input type="text" name="fileName"/><br/>
    file:<input type="file" name="file"><br/>
    <input type="submit" value="上传">
</form>
</body>
</html>

创建上传类

@RestController
public class UploadController {
    /**
     * 文件上传
     * @param file 页面中  type="file" name="file"
     * @param fileName 页面中 type="text" name="fileName"
     * @return 文件上传路径
     * @throws Exception
     */
    @RequestMapping("/execUpload")
    public String upload(MultipartFile file  , String fileName) throws  Exception{
        //开始
        System.err.println("upload s ...");
        System.err.println("fileName:" + fileName);
        String originFileName = file.getOriginalFilename();
        System.err.println("originFileName:" + originFileName);
        /**
         * 获取文件类型
         *
         */
        String fileType = originFileName.substring(originFileName.lastIndexOf("."),originFileName.length());
        /**
         * 获取项目webapp目录下的upload的路径
         */
        String prePath  = this.getClass().getResource("/").getPath() + "static" + File.separator + "upload";
        System.err.println("prePath:" + prePath);
        /**
         * 上传保存后新的文件名称
         */
        String newFileName = UUID.randomUUID().toString() + fileType;
        System.err.println("newFileName:" + newFileName);
        InputStream inputStream = file.getInputStream();
        File newFile = new File(prePath + File.separator + newFileName);
        if(!newFile.getParentFile().exists()){
            newFile.getParentFile().mkdirs();
        }
        OutputStream outputStream = new FileOutputStream(newFile);
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(b)) > 0){
            outputStream.write(b,0,len);
        }
        inputStream.close();
        outputStream.close();
        System.err.println("upload e ...");
        return newFile.getAbsolutePath();
    }
}

上传成功,可以通过http://IP:Port/项目名/static/upload/文件名 访问