文件的上传
servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan base-package="com.hanqi.controller" /> <mvc:annotation-driven /> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上传文件的总大小, 单位是b --> <property name="maxUploadSize" value="10485760"></property> <!-- 上传单个文件的大小, 单位是b --> <property name="maxUploadSizePerFile" value="5000000"></property> <!-- 默认的字符集 --> <property name="defaultEncoding" value="utf-8"></property> </bean> </beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>hanqi</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 启动时加载 --> <!-- 当数值大于等于0的时候, 启动时加载, 数值越小, 优先级越高 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>hanqi</servlet-name> <url-pattern>*.form</url-pattern> </servlet-mapping> </web-app>
TestControllor.java
@Controller @RequestMapping("/file") public class TestFileController { // ajax方式传递 @ResponseBody @RequestMapping("/ajaxUpload") public String ajaxUpload( HttpServletRequest request, MultipartFile myfile2, String desp, Model model) { StringBuffer buffer = new StringBuffer("{"success":true}"); String name = myfile2.getOriginalFilename(); System.out.println(name); return buffer.toString(); } // 跳转页面 @RequestMapping("/upload") public String upload(HttpServletRequest request, MultipartFile myfile, String desp, Model model) { // 获取服务器上的物理路径 String path = request.getServletContext().getRealPath("/upload"); String filename = myfile.getOriginalFilename();// 文件名+扩展名 String orgName = String.valueOf(new Date().getTime()); String suffixName = filename.substring(filename.lastIndexOf(".")); File file = new File(path + "/" + orgName + suffixName); try { myfile.transferTo(file); model.addAttribute("msg", "上传成功 !"); } catch (IllegalStateException e) { model.addAttribute("msg", "上传失败 !"); e.printStackTrace(); } catch (IOException e) { model.addAttribute("msg", "上传失败 !"); e.printStackTrace(); } return "page/success"; } }
index.jsp 进行文件选择的页面
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $(function() { $("#btn").click(function() { var f = new FormData($("#fmData")[0]); $.ajax({ type : "post", data : f, dataType : "json", contentType : false, processData : false, url : "file/ajaxUpload.form", success : function(data) { if (data.success) { alert("success !"); } else { alert("fail !"); } }, error : function() { alert("error !"); } }); }); }); </script> <h1>文件上传(ajax)</h1> <form id="fmData"> 文件描述: <input name="desp" /><br> <input type="file" name="myfile2" /><br> <input id="btn" type="button" value="Submit" /><br> </form> <h1>文件上传(页面跳转)</h1> <form action="file/upload.form" method="post" enctype="multipart/form-data"> 文件描述: <input name="desp" /><br> <input type="file" name="myfile" /><br> <input type="submit" value="Submit" /><br> </form>
sucess.jsp
<body> ${msg } </body>
文件的下载
TestFileControllor.java
@Controller @RequestMapping("/file") public class TestFileController { @RequestMapping("/redirectIndex") public String redirectIndex(HttpServletRequest request) { String realPath = request.getServletContext().getRealPath("/upload"); File orgFile = new File(realPath); File[] files = orgFile.listFiles(); List<String> list = new ArrayList<String>(); list.add(realPath); for(File f : files) { list.add(f.getName()); } request.getSession().setAttribute("fileList", list); return "redirect:/index.jsp"; } }
index.jsp
<a href="test.jsp">test.jsp</a><br> <a href="upload/javaweb.pdf" download>下载javaweb</a><br> <br> <% List<String> list = (List<String>) session.getAttribute("fileList"); if (list != null) { /* for (String s : list) { out.print("<a href='#'>" + s + "</a><br>"); } */ for (int i = 1; i < list.size(); i++) { out.print("<a href='" + list.get(0) + "\" + list.get(i) + "' download>" + list.get(i) + "</a><br>"); } } else { out.print("没有相关文件 !"); } %>
test.jsp
<body> <a href="file/redirectIndex.form">重定向到index.jsp</a> </body>