转载

文件上传的三种存储方式

1、本地上传

  • 新建springboot项目,引入Thymeleaf、web相关依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 在项目resource目录下新建templates文件夹并创建上传文件页面upload.html:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
    <form action="upload" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="file">
    <input type="submit" value="提交">
</form>
</body>
</html>
  • 创建success.html页面:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>上传成功</title>
</head>
<body>
<div th:if="${fileName}">
    <h2 th:text="|${fileName} 上传成功,存储路径为 :${path}|"> </h2>
</div>
</body>
</html>
  • 再创建一个error.html页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>上传失败</title>
</head>
<body>
<div th:if="${fileName}">
    <h2 th:text="|${fileName} 上传失败,失败原因为 :${msg}|"> </h2>
</div>
</body>
</html>
  • 新建uploadController
@Controller
@RequestMapping("/")
public class UploadController {
    
    @Autowired
    private UploadService uploadService;

    @GetMapping("/upload")
    public String to_upload(){
        return "upload";
    }

    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request, Model model){
        if (file!=null){
            Map map=uploadService.localUpload(file);
            model.addAllAttributes(map);
            return "success";
        }
        model.addAttribute("fileName",file.getOriginalFilename());
        model.addAttribute("msg","参数错误!");
        return "error";
    }
}
  • service
public interface UploadService {

    Map<String,Object> localUpload(MultipartFile file);

}
  • service实现类
@Service
public class UploadServiceImpl implements UploadService {

    @Override
    public Map<String, Object> localUpload(MultipartFile file) {
        Map<String, Object> resultMap=new HashMap<>(2);
        try {
            //原文件名加上时间戳作为上传后保存的文件名
            String fileName=System.currentTimeMillis()+file.getOriginalFilename();
            //指定目标文件名,此处将文件保存在项目的resource目录下,也可以保存在本地的其他目录下
            String destFileName=System.getProperty("user.dir")
                    +File.separator+"src"
                    +File.separator+"main"
                    +File.separator+"resources"
                    +File.separator+"upload"
                    +File.separator+fileName;
            //新建目标文件
            File destFile = new File(destFileName);
            //创建目标文件的存储路径
            destFile.getParentFile().mkdirs();
            //将前端接收的文件转化为目标文件
            file.transferTo(destFile);
            //将上传后的文件名和存储路径返回
            resultMap.put("fileName",fileName);
            resultMap.put("path",destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultMap;
    }
}
  • 在项目的resource目录新建application.yml配置文件,添加配置信息
server:
  port: 8899    #端口
spring:
  thymeleaf:
    prefix: classpath:/templates/   #前端页面文件路径
    suffix: .html                   #前端页面文件后缀名
  • 启动项目,浏览器输入 http://localhost :8899/upload

文件上传的三种存储方式

  • 选择一张名为test.jpg的图片后提交,

文件上传的三种存储方式

  • 上传成功

文件上传的三种存储方式

  • 在项目的resource目录下可以找到刚刚上传的文件

文件上传的三种存储方式

  • 再选择一个稍微大一点的文件进行上传,一个10MB的压缩包

文件上传的三种存储方式

上传失败

文件上传的三种存储方式

控制台显示错误信息

org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
    at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl$FileItemStreamImpl$1.raiseError(FileUploadBase.java:633) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.checkLimit(LimitedInputStream.java:76) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:135) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at java.io.FilterInputStream.read(FilterInputStream.java:107) ~[na:1.8.0_201]
    at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:98) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:68) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:293) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.connector.Request.parseParts(Request.java:2855) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.connector.Request.parseParameters(Request.java:3194) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.connector.Request.getParameter(Request.java:1116) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:381) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:84) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200) ~[tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:836) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1747) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_201]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_201]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.19.jar:9.0.19]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_201]

原因是上传的文件大小超过限制,因为默认的最大上传文件不能超过1MB,如果需要上传更大的文件,就需要在appliction.yml文件中添加以下配置:

servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB

文件上传的三种存储方式

重新启动项目,再次上传

文件上传的三种存储方式

查看resource下的upload文件夹

文件上传的三种存储方式

没问题

原文  https://segmentfault.com/a/1190000022113275
正文到此结束
Loading...