[Spring Boot] 利用MultipartFile进行文件上传和下载 的开发

MultipartFile

在Spring MVC中,Apache提供了一个Commons FileUpload库方便咱们进行文件的上传web

Package org.springframework.web.multipart
Multipart resolution framework for handling file uploads.**
Interface MultipartFile

    All Superinterfaces:
        InputStreamSource

    All Known Implementing Classes:
        CommonsMultipartFile, MockMultipartFile

Controller

经过List<>传递多个文件,也能够经过一个MultipartFile[]数组的方式,
而若是你须要一次只传递一个文件,只需将参数声明为MultipartFile multipartFile
@PostMapping(value = "/files", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)   <=== 设置content
public ResponseEntity<Map<String, String>> uploadFile(@RequestParam(value = "file", required = true)
                                                                              List<MultipartFile> multipartFile){
        
        return null;
    }

一个MultipartFile对象中包含了如下方法:spring

  1. getBytes()** 返回file的二进制数组形式
    当你实现了一个保存到数据库的代码时,咱们经过DB工具对文件data的column进行查看能够发现保存的内容

在这里插入图片描述

  1. getContentType() 返回String表示文件类型
    在这里插入图片描述数据库

  2. isEmpty() 是否为空‘
    在这里插入图片描述
    在这里插入图片描述api

    具体实现类MockMultipartFile Class:经过byte[] 保存 文件的二进制数据,isEmpty()则时判断数组的长度数组

  3. getInputStream() new一个ByteArrayInputStream(字节数组输入流)的对象,返回InputStream。mvc

  4. getName() 返回multipart form参数的名称app

  5. getOriginalFilename() 返回客户端文件系统中的原始文件名,它可能包含路径信息。svg

  6. getResource() 得到一个MultipartFile对象工具

  7. getSize() 返回content数组的大小,这个很好理解测试

  8. transferTo(File dest) 将接收到的文件传输到给定的目标文件。

  9. transferTo(Path dest) 将接收到的文件传输到给定的目标文件。

Config

在Spring Mvc中,咱们经过mvc.xml来限制文件,在Spring Boot里,咱们须要在application.properties里面添加key-value形式的参数。它将在server启动的时候,初始化你的设置。

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB
在这里插入图片描述
在这里插入图片描述

@ConfigurationProperties(
    prefix = "spring.servlet.multipart",
    ignoreUnknownFields = false
)
public class MultipartProperties {
    private boolean enabled = true;
    private String location;
    private DataSize maxFileSize = DataSize.ofMegabytes(1L);
    private DataSize maxRequestSize = DataSize.ofMegabytes(10L);
    private DataSize fileSizeThreshold = DataSize.ofBytes(0L);
    private boolean resolveLazily = false;

    public MultipartProperties() {
    }

    public boolean getEnabled() {
        return this.enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public String getLocation() {
        return this.location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public DataSize getMaxFileSize() {
        return this.maxFileSize;
    }

    public void setMaxFileSize(DataSize maxFileSize) {
        this.maxFileSize = maxFileSize;
    }

    public DataSize getMaxRequestSize() {
        return this.maxRequestSize;
    }

    public void setMaxRequestSize(DataSize maxRequestSize) {
        this.maxRequestSize = maxRequestSize;
    }

    public DataSize getFileSizeThreshold() {
        return this.fileSizeThreshold;
    }

    public void setFileSizeThreshold(DataSize fileSizeThreshold) {
        this.fileSizeThreshold = fileSizeThreshold;
    }

    public boolean isResolveLazily() {
        return this.resolveLazily;
    }

    public void setResolveLazily(boolean resolveLazily) {
        this.resolveLazily = resolveLazily;
    }

    public MultipartConfigElement createMultipartConfig() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
        map.from(this.fileSizeThreshold).to(factory::setFileSizeThreshold);
        map.from(this.location).whenHasText().to(factory::setLocation);
        map.from(this.maxRequestSize).to(factory::setMaxRequestSize);
        map.from(this.maxFileSize).to(factory::setMaxFileSize);
        return factory.createMultipartConfig();
    }
}

在Spring MVC中,咱们是经过这样设置的

<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
	p:defaultEncoding="UTF-8"   请求的编码格式
	p:maxUploadSize="10485760"  上传文件的字节大小 
	p:uploadTempDir="fileUpload/temp" 上传文件的临时路径
 >
</beans:bean>

经过Spring Web Mock测试文件上传

@RunWith(SpringRunner.class)
@SpringBootTest
public class FileUploadApplicationTest{

    @Autowired
    private WebApplicationContext webApplicationContext;
    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @After
    public void cleanUp() {
        mockMvc = null;
    }

    @Test
    public void uploadFile() throws Exception{
        MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
                MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
        MockMultipartHttpServletRequestBuilder mockMulHttpServletRequestBuilder = multipart("/api/fileupload/file");
        File testFile = new File("C:\\test.pdf");

        MockMultipartFile mockMultipartFile = new MockMultipartFile("file",
                "test.pdf",
                MediaType.APPLICATION_PDF_VALUE, new FileInputStream(testFile));
        mockMulHttpServletRequestBuilder.file(mockMultipartFile);

        MvcResult result = mockMvc.perform(mockMulHttpServletRequestBuilder)
                .andExpect(status().isAccepted())
                .andExpect(content().contentType(contentType))
                .andReturn();
    }