SpringMVC-文件上传




web.xml:

<?xml version="1.0" encoding="UTF-8"?>



    
        springmvc
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath:springmvc-servlet.xml
        
        1
    
    
        springmvc
        /
    

    
    
        CharacterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            utf-8
        
    
    
        CharacterEncodingFilter
        /*
    



springmvc-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>


    
    


    
    
        
            
                
            
            
                
                    
                        
                    
                
            
        
    


    
    
        
        
    

    
    
        
        
        
        
        
    



首页:


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

  
    $Title$
  
  

<%--
  enctype="multipart/form-data"
  enctype就是encodetype就是编码类型的意思
  multipart/form-data是指表单数据有多部分构成,既有文本数据,又有文件等二进制数据的意思
--%>
  

FileController

package com.kakafa.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


@RestController
public class FileController {

    //方法一
    //@RequestParam("file")将jsp页面中name=file的控件得到的文件封装成CommonsMultipartFile对象
    //如果是多个文件批量上传,则CommonsMultipartFile为数组即可
    @RequestMapping("/upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //获取文件名:file.getOriginalFilename()
        String filename = file.getOriginalFilename();

        //如果文件名为空则直接回到首页
        if (filename.equals("")){
            return "redirect:/index.jsp";
        }

        //上传路径保存设置
        //request.getServletContext().getRealPath("/sss")获得当前运行文件在服务器上的绝对路径
        String path = request.getServletContext().getRealPath("/sss");
        System.out.println("=======path:"+path);

        //如果路径不存在,创建一个
        File realPath=new File(path);
        if (!realPath.exists()){
            realPath.mkdir();//mkdir()是创建文件夹,createNewFile()是创建文件
        }
        System.out.println("=======上传文件保存地址:realPath"+realPath);

        InputStream is = file.getInputStream();
        FileOutputStream fos = new FileOutputStream(new File(realPath, filename));
        //读取写出
        int len=0;
        byte[] buffer=new byte[1024];
        while((len=is.read(buffer))!=-1){
            fos.write(buffer,0,len);
            fos.flush();//flush()方法将输入流和输出流中的缓冲进行刷新,使缓冲区中的元素及时做输入和输出,而不必等缓冲区满
        }
        fos.close();
        is.close();

        return "redirect:/index.jsp";
    }

    //方法二
    @RequestMapping("/upload2")
    public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //上传路径保存设置
        String path = request.getServletContext().getRealPath("/sss");
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        //上传文件地址
        System.out.println("上传文件保存地址:"+realPath);

        //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
        file.transferTo(new File(realPath+"/"+ file.getOriginalFilename()));

        return "redirect:/index.jsp";
    }
}


测试结果:


注意:

1)request.getServletContext()方法报红问题

解决:getServletContext()方法是Servlet3.0添加的,所以需要引入3.0以上的jar包


2)报错:Error creating bean with name 'multipartResolver': Failed to introspect bean class

原因:没有commons-fileupload包导致的

解决:pom.xml导包,并且记得把包加入到lib中

        
            commons-fileupload
            commons-fileupload
            1.3.1
        

网页文件上传所需要的是 commons-fileupload 包,而网页文件下载所需要的是commons-io 包