java中的文件上傳




[Java] Spring2文件上传实例 [复制链接]

   


项目结构视图:

web.xml文件内容:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  5. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  6. <servlet>
  7.   <servlet-name>spring-action</servlet-name>
  8.   <servlet-class>
  9.    org.springframework.web.servlet.DispatcherServlet
  10.   </servlet-class>
  11.   <load-on-startup>1</load-on-startup>
  12. </servlet>
  13. <servlet-mapping>
  14.   <servlet-name>spring-action</servlet-name>
  15.   <url-pattern>*.mhtml</url-pattern>
  16. </servlet-mapping>
  17. <welcome-file-list>
  18.   <welcome-file>testuploadfile.jsp</welcome-file>
  19. </welcome-file-list>
  20. </web-app>
复制代码

spring-action-servlet.xml文件内容:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  5. <!--
  6. 使用Spring已集成的Commons FileUpload上传组件。
  7. 1.为了让DispatcherServlet处理MultipartRequest,
  8. 在Spring配置文件中声明一个MultipartResolver。
  9. 这样一旦某个Request是一个MultipartRequest,
  10. 它就会首先被MultipartResolver处理,然后再转发到相应的Controller。
  11. -->
  12. <bean id="multipartResolver"
  13.   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  14.   <!-- set the max upload size10MB -->
  15.   <property name="maxUploadSize">
  16.    <value>10485760</value>
  17.   </property>
  18. </bean>
复制代码

  1. <!--
  2. 2.配置一个Controller,来处理上传的文件。
  3. -->
  4. <bean name="fileUploadController" autowire-candidate="false"
  5.   class="test.web.controller.uploadfile.FileUploadController">
  6.   <property name="commandClass" value="java.lang.Object" />
  7.   <!-- 上传失败时跳转页面 -->
  8.   <property name="formView" value="/user/err.jsp" />
  9.   <!-- 上传成功时跳转页面 -->
  10.   <property name="successView"
  11.    value="redirect:/testuploadfile.jsp" />
  12.   <property name="uploadDir" value="c:/testUploadFile/" />
  13. </bean>
复制代码
  1. <!--
  2. 3.配置一个URL映射控制器,直接将URL映射到相应的控制器处理。
  3. -->
  4. <bean id="urlMapping"
  5.   class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  6.   <property name="mappings">
  7.    <props>
  8.     <prop key="/testuploadfile.mhtml">
  9.      fileUploadController
  10.     </prop>
  11.    </props>
  12.   </property>
  13. </bean>
复制代码
  1. <!--
  2. 4.配置一个视图解析器,将逻辑视图名解析为一个用模板文件(如JSP或Velocity模板)渲染的视图对象。
  3. -->
  4. <bean id="viewResolver"
  5.   class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  6.   <property name="requestContextAttribute" value="rc" />
  7.   <property name="viewClass"
  8.    value="org.springframework.web.servlet.view.JstlView" />
  9.   <property name="prefix" value="" />
  10.   <property name="suffix" value=".jsp" />
  11. </bean>
  12. </beans>
复制代码

FileUploadController.java文件内容:
  1. package test.web.controller.uploadfile;
  2. import java.io.File;
  3. import java.util.Iterator;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. import org.springframework.validation.BindException;
  7. import org.springframework.web.multipart.MultipartFile;
  8. import org.springframework.web.multipart.MultipartHttpServletRequest;
  9. import org.springframework.web.servlet.ModelAndView;
  10. import org.springframework.web.servlet.mvc.SimpleFormController;
  11. public class FileUploadController extends SimpleFormController {
  12. private String uploadDir;//上传文件路径
  13. public void setUploadDir(String uploadDir) {
  14.   this.uploadDir = uploadDir;
  15. }
  16. public String getUploadDir() {
  17.   return this.uploadDir;
  18. }
  19. protected ModelAndView onSubmit(HttpServletRequest request,
  20.    HttpServletResponse response, Object cmd, BindException errors)
  21.    throws Exception {
  22.   uploadFile(request);
  23.   return new ModelAndView(getSuccessView());
  24. }
  25. private void uploadFile(HttpServletRequest request) {
  26.   // 转型为MultipartHttpRequest:
  27.   MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  28.   // 遍历所有文件域,获得上传的文件
  29.   for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
  30.    String key = (String) it.next();
  31.    MultipartFile file = multipartRequest.getFile(key);
  32.    saveFile(file);
  33.   }
  34. }
  35. private void saveFile(MultipartFile file) {
  36.   if (file == null || file.isEmpty())
  37.    return;
  38.   String filename = file.getOriginalFilename();
  39.   String localfileName = uploadDir + filename;
  40.   // 写入文件
  41.   File source = new File(localfileName.toString());
  42.   try {
  43.    file.transferTo(source);
  44.   } catch (Exception e) {
  45.    e.printStackTrace();
  46.   }
  47. }
  48. }
复制代码

testuploadfile.jsp文件内容:

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"%>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  3. <html>
  4. <head>
  5.   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  6.   <title>Insert title here</title>
  7.   <style>
  8.    .addAttachFileUrl{
  9.     position: relative;
  10.     font-size: 12px;
  11.    }
  12.    .file {
  13.     position: absolute;
  14.     width: 1px;
  15.     left: -3px;
  16.     filter: Alpha(opacity=0);
  17.     cursor: hand;
  18.     top: -3px;
  19.    }
  20.    .filelistItem {
  21.     display: block;
  22.     background: #ffffcc;
  23.     font: "宋体";
  24.     font-size: 12px;
  25.    }
  26.   </style>
  27.   <script type="text/javascript">
  28.     var i=1;
  29.     //文件上传
  30.     var attachname = "attach_";
  31.     function addFile(obj){
  32.      if(obj.value.length>0){
  33.       var fileNewInput = document.createElement("<input type='file' name='"+
  34.       attachname + i + "' class='file' onchange='addFile(this)'/>");
  35.       var fileName = document.createElement("span");
  36.       fileName.className = "filelistItem";
  37.       fileName.innerHTML = obj.value+
  38.       "  <a href='javascript:void(0)' onclick='delFile(this)'>删除</a>";
  39.       fileName.appendChild(obj);
  40.       document.getElementById("filelist").appendChild(fileName);
  41.       document.getElementById("filebutton").appendChild(fileNewInput)
  42.       obj.style.display="none";
  43.       i = i + 1;
  44.      }
  45.     }
  46.     function delFile(obj){
  47.      document.getElementById("filelist").removeChild(obj.parentNode)
  48.     }
  49.      </script>
  50. </head>
  51. <body>
  52.   <FORM id="myForm" method="POST" enctype="multipart/form-data"
  53.   action="testuploadfile.mhtml">
  54.    上传附件:
  55. <div id="filelist"></div>
  56.    <br />
  57.    <a class="addAttachFileUrl" href="javascript:void(0)" id="filebutton">点击添加附件
  58.     <input type="file" name="file_0" class="file"
  59.      onchange="addFile(this)" /> </a>
  60.    <br />
  61.    <input type="submit" value="提交">
  62.   </FORM>
  63. </body>
  64. </html>
复制代码

你可能感兴趣的:(java)