天天看點

SpringMVC教程3[檔案上傳下載下傳及靜态資源處理]

SpringMVC教程2[處理及響應請求]

一、檔案上傳

1.引入相關jar包

SpringMVC教程3[檔案上傳下載下傳及靜态資源處理]
maven坐标

<!-- fileUpload 解析上傳的檔案用到的jar -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>      

2.頁面表單資訊

表單送出方式必須是post方式送出,enctype必須是multipart/form-data

<form action="upload" method="post" enctype="multipart/form-data">
    <table>
        <tr>
            <td>使用者名</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>使用者密碼</td>
            <td><input type="password" name="password"></td>
        </tr>
        
        <tr>
            <td>使用者圖像</td>
            <td><input type="file" name="userface"></td>
        </tr>
        <tr>
            <td><input type="submit" value="注冊"></td>
        </tr>
    </table>
</form>      
SpringMVC教程3[檔案上傳下載下傳及靜态資源處理]

3.Controller中接收資料

/**
 * 檔案上傳案例
 * @author dpb【波波烤鴨】
 *
 */
@Controller
public class UserController {

    /**
     * 上傳的資料通過MultipartFile對象接收
     * @param username
     * @param password
     * @param userface
     * @throws Exception
     * @throws IOException
     */
    @RequestMapping("/upload")
    @ResponseBody
    public void upload(String username,String password
            ,MultipartFile userface) throws Exception, IOException{
        System.out.println(username+","+password);
        userface.transferTo(new File("c:/tools/","123.png"));
    }
    
}      

4.配置檔案中修改

<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
        id="multipartResolver" >
        <!-- 設定上傳檔案資訊參數 -->
        <!-- 設定檔案上傳的最大尺寸 -->
        <property name="maxUploadSize">
            <value>5242880</value>
        </property>
    </bean>      
SpringMVC教程3[檔案上傳下載下傳及靜态資源處理]

二、檔案下載下傳

1.方式一:基于ResponseEntity實作

@RequestMapping("/testHttpMessageDown")
public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
    // 需要下載下傳的檔案
    File file = new File("E://123.jpg");
    byte[] body = null;
    InputStream is = new FileInputStream(file);
    body = new byte[is.available()];
    is.read(body);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", "attchement;filename=" + file.getName());
    HttpStatus statusCode = HttpStatus.OK;
    ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
    return entity;
}      

方式二:通用下載下傳實作

@RequestMapping("/exportExcel")
public void exportExcel(HttpServletRequest request,HttpServletResponse response) throws IOException{
    File file = new File("d://owned.xls");
    //設定響應頭和用戶端儲存檔案名
    response.setCharacterEncoding("utf-8");
    response.setContentType("multipart/form-data");
    response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
    try {
        //打開本地檔案流
        InputStream inputStream = new FileInputStream(file);
        //激活下載下傳操作
        OutputStream os = response.getOutputStream();
        //循環寫入輸出流
        byte[] b = new byte[2048];
        int length;
        while ((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
        }
        // 這裡主要關閉。
        os.close();
        inputStream.close();
    } catch (Exception e){
        
        throw e;
    }
}      

三、靜态資源處理

SpringMVC教程3[檔案上傳下載下傳及靜态資源處理]

3.1 在web.xml中配置default servlet

<!-- 防止資源檔案被spring MVC攔截 -->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>      

3.2在配置檔案中通過标簽設定

<!--  防止資源檔案被spring MVC攔截--> 
     <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/>  
     <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/>  
     <mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/>       

   例如,浏覽器發送http://localhost:8080/static/img/01.png請求,該請求符合/static/img/*,此時,*代表01.png,那麼springmvc會将01.png補充到對應的location後面,進而查找到檔案。

   這裡需要注意:

   * 表示一層路徑

   ** 表示多層路徑映射