使用fileupload或Spinrg上傳文件

導jar包css

<dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>
  </dependencies>

配置web.xmlhtml

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <!-- 加載前端控制器 -->
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--
           加載配置文件
     -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <!--配置解決中文亂碼的過濾器-->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

spring配置文件前端

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

<!--spring註解掃描-->
   <context:component-scan base-package="cn.itcast"></context:component-scan>

    <!-- 配置sprigmvc視圖解析器:解析邏輯試圖;
        後臺返回邏輯試圖:index
        視圖解析器解析出真正物理視圖:前綴+邏輯試圖+後綴====/WEB-INF/jsps/index.jsp
    -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--前端控制器,哪些靜態資源不攔截-->
<!--    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>-->

<!--springMVC註解掃描-->
    <mvc:annotation-driven/>
</beans>

fileupload上傳文件
注意使用該方法必定不要在springmvc.xml中配置文件解析器對象java

@RequestMapping("/fileupload1")
    public String fileupload1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("文件上傳...");

        // 上傳的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads");
        // 判斷,該路徑是否存在
        File file = new File(path);
        if(!file.exists()){
            // 建立該文件夾
            file.mkdirs();
        }

        // 解析request對象,獲取上傳文件項
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 解析request
        List<FileItem> items = upload.parseRequest(request);
        String itemNo = "";

        // 遍歷
        for(FileItem item:items){
          if(!item.isFormField()){
                // 獲取上傳文件的名稱
                String filename = item.getName();
                // 把文件的名稱設置惟一值,uuid
                String uuid = UUID.randomUUID().toString().replace("-", "");
                filename = uuid+"_"+filename;
                // 完成文件上傳
                item.write(new File(path,filename));
                // 刪除臨時文件
                item.delete();
            }
        }
        return "success";
    }

springMVC上傳文件web

@RequestMapping("/fileupload2")
    public String fileupload2(HttpServletRequest request, MultipartFile upload) throws Exception {
        System.out.println("springmvc文件上傳...");

        // 使用fileupload組件完成文件上傳
        // 上傳的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads");
        // 判斷,該路徑是否存在
        File file = new File(path);
        if(!file.exists()){
            // 建立該文件夾
            file.mkdirs();
        }

        // 說明上傳文件項
        // 獲取上傳文件的名稱
        String filename = upload.getOriginalFilename();
        // 把文件的名稱設置惟一值,uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid+"_"+filename;
        // 完成文件上傳
        upload.transferTo(new File(path,filename));

        return "success";
    }

使用該方法要在springmvc.xml中配置文件解析器對象spring

<!--配置文件解析器對象-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760" />
    </bean>

前端提交表單頁面api

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>文件上傳</h3>


<form action="user/fileupload1" method="post" enctype="multipart/form-data">
   <%-- 選擇文件:--%><input type="file" name="upload" /><br/>
    <input type="submit" value="上傳" />
</form>

<form action="user/fileupload2" method="post" enctype="multipart/form-data">
    選擇文件:<input type="file" name="upload" /><br/>
    <input type="submit" value="上傳" />
</form>
</body>
</html>
相關文章
相關標籤/搜索