SpringMVC上傳下載

f663x 9年前發布 | 4K 次閱讀 Java SpringMVC

springmvc上傳下載功能 參照網上代碼寫了一個簡單的例子

 

1、需要導入jar包:ant.jar、commons-fileupload.jar、connom-io.jar。當然spring jar包不可缺少的哦  我這里用的是spring+springmvc+hibernate  可以到官網上直接下載springmvcjar即可


2、springmvc.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/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">


<!-- 掃描包 -->
<context:component-scan base-package="com.ai.customer" />

 <!-- 啟動注解 -->
 <mvc:annotation-driven />


<!-- 文件上傳 -->
 <bean id="multipartResolver"  
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <!-- 設置上傳文件的最大尺寸為10MB -->  
   <property name="maxUploadSize">  
       <value>10000000</value>  
   </property>  
  </bean>  


<!--  靜態文件訪問 -->
 <mvc:default-servlet-handler/> 
 <!-- 對模型視圖名稱的解析,即在模型視圖名稱添加前后綴 --> 
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >

    <property name="prefix" value="/"/>
    <property name="suffix" value=".jsp"/>    
 </bean> 

</beans>

3、web.xml配置



<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:config/spring/spring-*.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
<filter>
    <filter-name>codeUTF-8</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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>codeUTF-8</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

4、程序代碼塊



package com.ai.customer.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FileUploadController {

    /*
     * SpringMVC中的文件上傳
     * @第一步:由于SpringMVC使用的是commons-fileupload實現,故將其組件引入項目中
     * @這里用到的是commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar
     * @第二步:spring-mvx中配置MultipartResolver處理器。可在此加入對上傳文件的屬性限制
     *  <bean id="multipartResolver"  
     *  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     *     <!-- 設置上傳文件的最大尺寸為10MB -->  
     *        <property name="maxUploadSize">  
     *            <value>10000000</value>  
     *         </property>  
     * </bean> 
     * 第三步:在Controller的方法中添加MultipartFile參數。該參數用于接收表單中file組件的內容
     *第四步:編寫前臺表單。注意enctype="multipart/form-data"以及<input type="file" name="****"/>
     *  如果是單個文件 直接使用MultipartFile 即可
     */ 

    /**********************上傳代碼**************************/
    @RequestMapping("/upload.do")
    public ModelAndView upload(String name,
            //上傳多個文件
            @RequestParam("file") MultipartFile[] file,
            HttpServletRequest request) throws IllegalStateException,
            IOException {

        //獲取文件 存儲位置
        String realPath = request.getSession().getServletContext()
                .getRealPath("/uploadFile");

        File pathFile = new File(realPath);

        if (!pathFile.exists()) {
            //文件夾不存 創建文件
            pathFile.mkdirs();
        }
        for (MultipartFile f : file) {

            System.out.println("文件類型:"+f.getContentType());
            System.out.println("文件名稱:"+f.getOriginalFilename());
            System.out.println("文件大小:"+f.getSize());
            System.out.println(".................................................");
            //將文件copy上傳到服務器
            f.transferTo(new File(realPath + "/" + f.getOriginalFilename()));
             //FileUtils.copy
        }
        //獲取modelandview對象
        ModelAndView view = new ModelAndView();
        view.setViewName("redirect:index.jsp");
        return view;
    }



    /********下載代碼*************/
    @RequestMapping(value = "download.do")  
    public ModelAndView download(HttpServletRequest request,  
            HttpServletResponse response) throws Exception {  

//        String storeName = "Spring3.xAPI_zh.chm";  
        String storeName="房地.txt";
        String contentType = "application/octet-stream";  
        FileUploadController.download(request, response, storeName, contentType);  
        return null;  
    }  


    //文件下載 主要方法
    public static void download(HttpServletRequest request,  
            HttpServletResponse response, String storeName, String contentType
           ) throws Exception {  

        request.setCharacterEncoding("UTF-8");  
        BufferedInputStream bis = null;  
        BufferedOutputStream bos = null;  

        //獲取項目根目錄
        String ctxPath = request.getSession().getServletContext()  
                .getRealPath("");  

        //獲取下載文件露肩
        String downLoadPath = ctxPath+"/uploadFile/"+ storeName;  

        //獲取文件的長度
        long fileLength = new File(downLoadPath).length();  

        //設置文件輸出類型
        response.setContentType("application/octet-stream");  
        response.setHeader("Content-disposition", "attachment; filename="  
                + new String(storeName.getBytes("utf-8"), "ISO8859-1")); 
        //設置輸出長度
        response.setHeader("Content-Length", String.valueOf(fileLength));  
        //獲取輸入流
        bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
        //輸出流
        bos = new BufferedOutputStream(response.getOutputStream());  
        byte[] buff = new byte[2048];  
        int bytesRead;  
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
            bos.write(buff, 0, bytesRead);  
        }  
        //關閉流
        bis.close();  
        bos.close();  
    }  

}  

5、jsp頁面代碼 注意:設置表單中form表單的屬性為:enctype="multipart/form-data"



<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>


    <form action="upload.do" method="post" enctype="multipart/form-data">

        <input type="text" name="name" />
        <br>
        <input type="file" name="file">
        <br>
        <input type="file" name="file" />

        <input type="submit" value="提交">
    </form>


</body>
</html>



 本文由用戶 f663x 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!