Spring MVC 处理文件上传

2022-05-17 16:26:17 浏览数 (1)

使用 HttpServletRequest 对象处理上传文件

代码语言:javascript复制
    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(HttpServletRequest request) {
        log.info("----fileUpload start----");
        log.info("className = {}, contextPath = {}, servletPath = {}", request.getClass().getName(), request.getContextPath(), request.getServletPath());

        final Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            log.info("key = {}, value = {}", entry.getKey(), Arrays.toString(entry.getValue()));
        }

        final MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        for (Map.Entry<String, List<MultipartFile>> entry : multipartHttpServletRequest.getMultiFileMap().entrySet()) {
            final List<MultipartFile> value = entry.getValue();
            for (MultipartFile file : value) {
                log.info("fileName = {}, fileOriginalFilename = {}, size = {} KB", file.getName(), file.getOriginalFilename(), file.getSize() / 1024);
            }
        }
        log.info("----fileUpload end----");
        return "upload successful";
    }

对应 cURL 描述

代码语言:javascript复制
curl --location --request POST 'localhost:4000/fileUpload' 
--form 'aaa="bbb"' 
--form 'def=@"/C:/Users/hp/Desktop/11111.sql"'

对应的 RestTemplate 描述

代码语言:javascript复制
    public String uploadTest() {
        log.info("--- uploadTest start ---");
        HttpHeaders headers = new HttpHeaders();
        //  请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        //  封装参数,千万不要替换为 Map 与 HashMap,否则参数无法传递
        MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add("aaa", "bbb");
        multiValueMap.add("def", new FileSystemResource("C:/Users/hp/Desktop/11111.sql"));
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(multiValueMap, headers);

        // 执行HTTP请求
        ResponseEntity<String> response = null;
        try {
            response = this.restTemplate.exchange("http://localhost:4000/fileUpload", HttpMethod.POST, requestEntity, String.class);
        } catch (HttpStatusCodeException e) {
            final HttpStatus httpStatus = e.getStatusCode();
            log.error("HttpStatusCodeException httpStatus = {}", httpStatus, e);
        } catch (RestClientException e) {
            log.error("RestClientException", e);
        }
        if (response != null) {
            //  输出结果
            final HttpStatus statusCode = response.getStatusCode();
            final int value = statusCode.value();
            log.info("rest template statusCode = {}, result = {}", value, response.getBody());
        }
        log.info("--- uploadTest end ---");
        return "OK";
    }

日志打印结果

代码语言:javascript复制
2021-05-06 18:44:42.849  controller.EmailController   : ----fileUpload start----
2021-05-06 18:44:42.849  controller.EmailController   : className = org.springframework.web.multipart.support.StandardMultipartHttpServletRequest, contextPath = , servletPath = /fileUpload
2021-05-06 18:44:42.849  controller.EmailController   : key = aaa, value = [bbb]
2021-05-06 18:44:42.850  controller.EmailController   : fileName = def, fileOriginalFilename = 11111.sql, size = 2 KB
2021-05-06 18:44:42.850  controller.EmailController   : ----fileUpload end----

直接使用 MultipartFile 对象获取上传的文件

代码语言:javascript复制
    @RequestMapping("/multipartFile")
    public String upload(@RequestParam("aaa") String abc, @RequestParam("def") MultipartFile file) throws IllegalStateException {
        log.info("abc = {}", abc);
        // 判断文件是否为空,空则返回失败页面
        if (file.isEmpty()) {
            return "failed";
        }
        log.info("className = {}, fileName = {}, fileOriginalFilename = {}, size = {} KB", file.getClass().getName(), file.getName(), file.getOriginalFilename(), file.getSize() / 1024);
        return "success";
    }

日志输出

代码语言:javascript复制
2021-05-06 20:06:36.578  INFO 3488 --- [nio-4000-exec-1] c.lagou.edu.controller.EmailController   : abc = bbb
2021-05-06 20:06:36.581  INFO 3488 --- [nio-4000-exec-1] c.lagou.edu.controller.EmailController   : className = org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile, fileName = def, fileOriginalFilename = 11111.sql, size = 2 KB

由此说明 MultipartFile 的实际类型为 org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile

多文件上传,将 MultipartFile 改为类型数组即可

In our example we are presenting demo for single and multiple file upload. So we have created two different methods for uploading the file. In single upload, the method should have the parameter as below with other parameters. @RequestParam("file") MultipartFile file And for multiple file upload , the parameter should be as below @RequestParam("file") MultipartFile[] file

代码片段

代码语言:javascript复制
package com.lagou.edu.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 测试 spring mvc fileUpload
 *
 * @author lik
 * @date 2021/5/6
 */
@Slf4j
@RestController
public class EmailController {

    @Autowired
    RestTemplate restTemplate;

    @RequestMapping(value = "/uploadTest")
    public String uploadTest() {
        log.info("--- uploadTest start ---");
        HttpHeaders headers = new HttpHeaders();
        //  请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        //  封装参数,千万不要替换为 Map 与 HashMap,否则参数无法传递
        MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add("aaa", "bbb");
        multiValueMap.add("def", new FileSystemResource("C:/Users/hp/Desktop/11111.sql"));
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(multiValueMap, headers);

        // 执行HTTP请求
        ResponseEntity<String> response = null;
        try {
            response = this.restTemplate.exchange("http://localhost:4000/fileUpload", HttpMethod.POST, requestEntity, String.class);
        } catch (HttpStatusCodeException e) {
            final HttpStatus httpStatus = e.getStatusCode();
            log.error("HttpStatusCodeException httpStatus = {}", httpStatus, e);
        } catch (RestClientException e) {
            log.error("RestClientException", e);
        }
        if (response != null) {
            //  输出结果
            final HttpStatus statusCode = response.getStatusCode();
            final int value = statusCode.value();
            log.info("rest template statusCode = {}, result = {}", value, response.getBody());
        }
        log.info("--- uploadTest end ---");
        return "OK";
    }

    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(HttpServletRequest request) {
        log.info("----fileUpload start----");
        log.info("className = {}, contextPath = {}, servletPath = {}", request.getClass().getName(), request.getContextPath(), request.getServletPath());

        final Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            log.info("key = {}, value = {}", entry.getKey(), Arrays.toString(entry.getValue()));
        }

        final MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        for (Map.Entry<String, List<MultipartFile>> entry : multipartHttpServletRequest.getMultiFileMap().entrySet()) {
            final List<MultipartFile> value = entry.getValue();
            for (MultipartFile file : value) {
                log.info("className = {}, fileName = {}, fileOriginalFilename = {}, size = {} KB", file.getClass().getName(), file.getName(), file.getOriginalFilename(), file.getSize() / 1024);
            }
        }
        log.info("----fileUpload end----");
        return "upload successful";
    }

    @RequestMapping("/multipartFile")
    public String upload(@RequestParam("aaa") String abc, @RequestParam("def") MultipartFile file) throws IllegalStateException {
        log.info("abc = {}", abc);
        // 判断文件是否为空,空则返回失败页面
        if (file.isEmpty()) {
            return "failed";
        }
        log.info("className = {}, fileName = {}, fileOriginalFilename = {}, size = {} KB", file.getClass().getName(), file.getName(), file.getOriginalFilename(), file.getSize() / 1024);
        return "success";
    }

    @RequestMapping("/multipartFiles")
    public String upload(@RequestParam("def") MultipartFile[] multipartFiles) throws IllegalStateException {
        for (MultipartFile file : multipartFiles) {
            log.info("className = {}, fileName = {}, fileOriginalFilename = {}, size = {} KB", file.getClass().getName(), file.getName(), file.getOriginalFilename(), file.getSize() / 1024);
        }
        return "success";
    }
}

参考

一个包含各Java 教程的网站:Java, Spring, Angular, Hibernate and Android https://www.concretepage.com/

0 人点赞