前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring MVC 处理文件上传

Spring MVC 处理文件上传

作者头像
acc8226
发布2022-05-17 16:26:17
4870
发布2022-05-17 16:26:17
举报
文章被收录于专栏:叽叽西

使用 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/

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用 HttpServletRequest 对象处理上传文件
  • 直接使用 MultipartFile 对象获取上传的文件
    • 多文件上传,将 MultipartFile 改为类型数组即可
    • 代码片段
    • 参考
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档