SpringMVC 配置servlet3.0 文件上传

2018-03-20 20:45:21
770次阅读
0个评论

StandardServletMultipartResolver解析器依赖于Servlet3.0对multipart的请求的支持

1.配置web.xml文件中的servlet,添加multipart-config:

<!-- SpringMVC -->  
<servlet>  
    <servlet-name>myWeb</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <init-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:springmvc/servlet.xml</param-value>  
    </init-param>  
    <load-on-startup>1</load-on-startup>  
    <multipart-config>  
        <!-- <location>/</location> -->  
        <max-file-size>5242880</max-file-size>  <!--单个文件最大大小:5MB-->  
        <max-request-size>20971520</max-request-size>   <!--所有文件最大大小:20MB-->  
        <file-size-threshold>0</file-size-threshold>    <!-- 超过这个大小直接存硬盘,而不是内存 -->  
    </multipart-config>  
</servlet>  
  
<servlet-mapping>  
    <servlet-name>myWeb</servlet-name>  
    <url-pattern>/</url-pattern>  
</servlet-mapping>

2.在servlet.xml中配置MultipartResolver


<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>

3.创建接收form表单的Controller:


import java.io.File;  
import java.io.IOException;  
import java.util.Map;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.Part;  
  
import org.springframework.stereotype.Controller;  
import org.springframework.util.StringUtils;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestParam;  
import org.springframework.web.bind.annotation.ResponseBody;  
  
import com.xjj.json.JsonResult;  
  
/** 
 * 文件上传 
 * @author XuJijun 
 * 
 */  
@Controller  
@RequestMapping("/servlet/file")  
public class FileUploadController {  
      
    /** 
     * 保存文件的目录,放在web目录、或一个指定的绝对目录下 
     */  
     private static final String SAVE_DIR = "uploadFiles";  
      
    @RequestMapping("/upload")  
    public @ResponseBody JsonResult upload(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, Object> p)  
            throws ServletException, IOException {  
  
        // 获取 web application的绝对路径  
        String appPath = request.getServletContext().getRealPath("");  
          
        // 构造文件存放的路径  
        String savePath = appPath + File.separator + SAVE_DIR;  
  
        // 如果文件存放路径不存在,则mkdir一个  
        File fileSaveDir = new File(savePath);  
        if (!fileSaveDir.exists()) {  
            fileSaveDir.mkdir();  
        }  
  
        for (Part part : request.getParts()) {  
            String fileName = extractFileName(part);  
            if(!StringUtils.isEmpty(fileName)){  
                part.write(savePath + File.separator + fileName);  
            }  
        }  
  
        return new JsonResult("200", "文件上传成功!", savePath);  
    }  
       
    /** 
     * 从content-disposition头中获取源文件名 
     *  
     * content-disposition头的格式如下: 
     * form-data; name="dataFile"; filename="PHOTO.JPG" 
     *  
     * @param part 
     * @return 
     */  
    private String extractFileName(Part part) {  
        String contentDisp = part.getHeader("content-disposition");  
        String[] items = contentDisp.split(";");  
        for (String s : items) {  
            if (s.trim().startsWith("filename")) {  
                return s.substring(s.indexOf("=") + 2, s.length()-1);  
            }  
        }  
        return "";  
    }  
  
}

其中,request.getParts()用来获取multipart,其中就包括文件。其他<input type="text">参数由@RequestParam Map<String, Object> 接收。

4:form表单提交文件以及其他数据:


<html>  
<head>  
<meta charset="UTF-8">  
    <link href="../resources/css/common.css" rel="stylesheet" />  
    <script src="../resources/js/jquery-2.1.4.js"></script>  
      
</head>  
  
<body>  
<h2>File Upload</h2>  
    <form method="post" enctype="multipart/form-data">  
        <input type="text" name="aaa"/><br/>  
        选择要上传的文件:<input type="file" name="file" size="60" /><br/>  
        <input type="file" name="file" size="60" /><br/>  
        <br/> <!-- <input type="submit" value="开始上传" /> -->  
    </form>  
      
    <input type="button" value="上传吧" onclick="upload()"/>  
</body>  
  
<script>  
    function upload(){  
        $("form").attr('action', "http://localhost:8080/MyJavaStudio/servlet/file/upload");  
        $("form").submit();  
    }  
</script>  
  
</html>


收藏00

登录 后评论。没有帐号? 注册 一个。