时间:2020-10-02 10:20:08 | 栏目:JAVA代码 | 点击:次
简单几步,实现SpringMVC+servlet3.0文件上传功能:
第一步:配置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>
第二步:在servlet.xml中配置MultipartResolver:
第三步:创建接收form表单的Controller:
package com.xjj.web.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> p接收。
第四步:form表单提交文件以及其他数据:
<html> <head> <meta charset="UTF-8"> <link href="../resources/css/common.css" rel="external nofollow" 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>
注:通过jQuery来submit表单,以自由拼装action url,自由定义提交按钮。
github:https://github.com/xujijun/MyJavaStudio
完整代码下载:MyJavaStudio_jb51.rar