简单文件上传

简单文件上传

效果

类似这样的表单提交,想要实现文件上传。

image-20210226204710366

前端页面demo

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="email" name="email"><br>
    <input type="password" name="password"><br>
    <input type="file" name="header" accept=".png,.jpg"><br>
    <input type="file" multiple name="lifePhotos"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

后端接收demo

SpringMVC中的实现

@Controller
@Slf4j
public class UploadController {
    @PostMapping("upload")
    @ResponseBody
    public WebResult upload(@RequestParam String email,
                            @RequestParam String password,
                            @RequestPart MultipartFile header,
                            @RequestPart List<MultipartFile> lifePhotos) throws IOException {
        WebResult result = null;
        if (header != null && !header.isEmpty()) {
            saveToOtherPlace(email, header, lifePhotos);
            result = new WebResult(1, "信息上传成功");
        } else {
            result = new WebResult(10, "信息上传失败");
        }
        return result;
    }

    private void saveToOtherPlace(String email, MultipartFile header, List<MultipartFile> lifePhotos) throws IOException {
        File headFile = new File("E:\\jingmin\\tmp\\" + email + "-header-" + header.getOriginalFilename());
        header.transferTo(headFile);
        log.info("用户{}的头像存储于{}", email, headFile.getAbsolutePath());
        for (int i = 0; i < lifePhotos.size(); i++) {
            MultipartFile file = lifePhotos.get(i);
            File lifeFile =
                    new File("E:\\jingmin\\tmp\\" + email + "-lifePhoto-" + i + file.getOriginalFilename());
            file.transferTo(lifeFile);
            log.info("用户{}的生活照存储于{}", email, lifeFile.getAbsolutePath());
        }
    }
}

如果是Spring项目,需要配置文件上传解析器

spring文档中对文件上传支持的说明:

Multipart Resolver

WebFlux

MultipartResolver from the org.springframework.web.multipart package is a strategy for parsing multipart requests including file uploads. There is one implementation based on Commons FileUpload and another based on Servlet 3.0 multipart request parsing.

To enable multipart handling, you need to declare a MultipartResolver bean in your DispatcherServlet Spring configuration with a name of multipartResolver. The DispatcherServlet detects it and applies it to the incoming request. When a POST with content-type of multipart/form-data is received, the resolver parses the content and wraps the current HttpServletRequest as MultipartHttpServletRequest to provide access to resolved parts in addition to exposing them as request parameters.

Apache Commons FileUpload

To use Apache Commons FileUpload, you can configure a bean of type CommonsMultipartResolver with a name of multipartResolver. You also need to have commons-fileupload as a dependency on your classpath.

Servlet 3.0

Servlet 3.0 multipart parsing needs to be enabled through Servlet container configuration. To do so:

  • In Java, set a MultipartConfigElement on the Servlet registration.
  • In web.xml, add a "<multipart-config>" section to the servlet declaration.

The following example shows how to set a MultipartConfigElement on the Servlet registration:

public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    // ...

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {

        // Optionally also set maxFileSize, maxRequestSize, fileSizeThreshold
        registration.setMultipartConfig(new MultipartConfigElement("/tmp"));
    }

}

Once the Servlet 3.0 configuration is in place, you can add a bean of type StandardServletMultipartResolver with a name of multipartResolver.

即,有两种方式:

  • 可以添加Apache Commons FileUpload的依赖,并在Spring中配置一个 CommonsMultipartResolver ,名字叫做 multipartResolver.
  • 也可以依靠Servlet3.0容器的支持,这种方式需要注册MultipartConfigElement并在web.xml中添加"<multipart-config>"配置

我没亲自在Spring下配过,但是可以参考这篇文章:https://blog.csdn.net/suifeng3051/article/details/51659731

如果是SpringBoot项目,自动配好了文件上传解析器

SpringBoot中文件上传解析器自动配置是MultipartAutoConfiguration类。实际上就是上面Spring中Servlet容器配置文件上传的自动配置。

注意,默认限制了文件上传的大小,有点小,可以在application.properties中改大一点:

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=200MB

局限性

前端一般想要上传预览,这个可以找插件来实现。

断点续传上传。HTTP/1.1中添加了几个断点续传的请求头,但是若想实现断点续传(上传),需要后端自己实现。几个可能的参考: https://blog.csdn.net/A1032453509/article/details/78045957 https://blog.csdn.net/xifeijian/article/details/8712439 https://futu.im/article/http-break-point-continue/ https://www.cnblogs.com/imwtr/p/5957391.html https://www.programmersought.com/article/82853841285/ 据说断点续传下载apache是支持的,断点续传上传tomcat要自己实现。(https://bbs.csdn.net/topics/300066608)