SpringMVC-文件上传


文件上传也是获得请求数据的一种,但是获得客户端的数据并不是一个普通的类型。

文件上传步骤

  1. 导入fileupload和io的包坐标
  2. 配置文件上传解析器
  3. 编写文件上传代码

1. 导入坐标

    
    
      commons-fileupload
      commons-fileupload
      1.3.3
    
    
      commons-io
      commons-io
      2.5
    

2. 配置文件上传解析器

value设置过大可能会导致超出tomcat限制导致文件为null

    
    
        
        
        
        
        
        
    

3. 编写文件上传代码

新建一个jsp文件为upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>


    上传文件


  
文件

编写Controller中文件获得方法

    // 上传文件
    @ResponseBody
    @RequestMapping("/upload")
    public String upload(@RequestParam(value = "file",required = false) MultipartFile file) throws IOException {
        if(file == null){
            return "抱歉,您没有传入文件";
        }else {
            System.out.println(file);
            // 获取上传文件名称
            String originalFilename = file.getOriginalFilename();
            // 存储
            file.transferTo(new File("文件路径"+originalFilename));
            return "上传文件成功!";
        }
    }