1. 程式人生 > >SpringMVC的檔案上傳和下載

SpringMVC的檔案上傳和下載

    SpringMVC會根據請求方法簽名的不同,將請求訊息中的資訊以一定的方式轉換並繫結到請求方法的引數中。在請求訊息到達真正呼叫處理方法的這段時間內,SpringMVC還會完成很多其他的工作,包括請求訊息轉換、資料轉換、資料格式化以及資料校驗。

一:SpringMVC實現檔案上傳

    為了實現檔案上上傳,必須將表單的method設定為POST,並將enctype設定為multipart/form-data,在這種情況下瀏覽器會把使用者選擇的檔案二進位制資料傳送給伺服器。SpringMVC為檔案上傳提供了直接的支援,用即插即用的MultipartResolver實現,因此SpringMVC的檔案上傳元件還需要依賴Apache Commons FileUpload的元件。

<!-- 檔案上傳元件 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>

    案例:SpringMVC的檔案上傳

        1、在SpringMVC.xml檔案中新增Bean檔案

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--上傳檔案大小限制 單位為位元組(10M)-->
        <property name="maxUploadSize">
            <value>10485760</value>
        </property>
        <!--請求的編碼格式 必須和jsp的pageEncoding屬性一致 以便正確讀取表單的內容 預設為IS0-8859-1 -->
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>

    2、編寫jsp頁面 分別是registerForm.jsp、userInfo.jsp、error.jsp   

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>使用者註冊</title>
</head>
<body>
    <h2>使用者註冊</h2>
    <form action="register" enctype="multipart/form-data" method="post">
        <table>
            <tr>
                <td>使用者名稱:</td>
                <td><input type="text" name="username"/></td>
            </tr>
            <tr>
                <td>請上傳圖片:</td>
                <td><input type="file" name="image"/></td>
            </tr>
            <tr>
                <td><input type="submit" name="註冊"/></td>
            </tr>
        </table>
    </form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h2>檔案下載</h2>
    <a href="download?filename=${requestScope.user.image.originalFilename}">
        ${requestScope.user.image.originalFilename}
    </a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    錯誤頁面
</body>
</html>

    3、Controller類

@RequestMapping("/register")
    public String register(HttpServletRequest request, @ModelAttribute User user, Model model)throws Exception{
        if(!user.getImage().isEmpty()){
            /**上傳檔案的路徑*/
            String path = request.getSession().getServletContext().getRealPath("/images/");
            System.out.println(path);
            /**上傳檔名*/
            String filename = user.getImage().getOriginalFilename();
            File filepath = new File(path,filename);
            /**判斷路徑是否存在 不存在則建立*/
            if(!filepath.getParentFile().exists()){
                filepath.getParentFile().mkdirs();
            }
            /**將上傳檔案儲存帶目標檔案中*/
            user.getImage().transferTo(new File(path+File.separator+filename));
            /**將使用者新增到model*/
            model.addAttribute("user",user);
            /**跳轉*/
            return "userInfo";
        }else{
            return "error";
        }
    }

    
package com.jz.demo;
import org.springframework.web.multipart.MultipartFile;
public class User {
    private String username;
    private MultipartFile image;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public MultipartFile getImage() {
        return image;
    }

    public void setImage(MultipartFile image) {
        this.image = image;
    }
}
@RequestMapping("/register")
    public String register(HttpServletRequest request, @ModelAttribute User user, Model model)throws Exception{
        if(!user.getImage().isEmpty()){
            /**上傳檔案的路徑*/
            String path = request.getSession().getServletContext().getRealPath("/images/");
            System.out.println(path);
            /**上傳檔名*/
            String filename = user.getImage().getOriginalFilename();
            File filepath = new File(path,filename);
            /**判斷路徑是否存在 不存在則建立*/
            if(!filepath.getParentFile().exists()){
                filepath.getParentFile().mkdirs();
            }
            /**將上傳檔案儲存帶目標檔案中*/
            user.getImage().transferTo(new File(path+File.separator+filename));
            /**將使用者新增到model*/
            model.addAttribute("user",user);
            /**跳轉*/
            return "userInfo";
        }else{
            return "error";
        }
    }


二:檔案下載

    SpringMVC提供了一個ResponseEntity型別,使用它可以很方便的定義返回的HttpHeaders。

    @RequestMapping(value="/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request,
                                           @RequestParam("filename") String filename,
                                           Model model)throws Exception{
        // 下載檔案路徑
        String path = request.getSession().getServletContext().getRealPath(
                "/images/");
        File file = new File(path+File.separator+ filename);
        HttpHeaders headers = new HttpHeaders();
        // 下載顯示的檔名,解決中文名稱亂碼問題
        String downloadFielName = new String(filename.getBytes("iso-8859-1"),"UTF-8");
        // 通知瀏覽器以attachment(下載方式)開啟圖片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        // application/octet-stream : 二進位制流資料(最常見的檔案下載)。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 201 HttpStatus.CREATED
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }