SpringMVC——實現文件上傳下載

參考:
http://blog.csdn.net/u012706811/article/details/51059419
http://blog.csdn.net/u012660464/article/details/53434331

一、文件上傳

1.引入依賴包

在pom.xml文件中添加如下內容,引入 commons-fileuploadcommons-io 兩個包。

<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.3</version>
</dependency>

2.spring-mvc.xml

<!--文件上傳-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--最大上傳大小(字節)-->
    <property name="maxUploadSize" value="1048576" />
</bean>

3.fileUpload.jsp

form中加入 enctype=”multipart/form-data” 屬性,表示將文件一二進制流傳輸,否則報錯。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>fileUpload —— 單個文件</title>
</head>
<body>
<h1 align = "center">文件上傳</h1>
<form action = "${website}FileController" enctype="multipart/form-data" method = "post">
    選擇文件:<input type="file" name = "file">
    <input type="submit" value = "提交">
</form>
</body>
</html>

4.Success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success</title>
</head>
<body>
<h1 align="center">Success!</h1>
</body>
</html>

5.index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2 align="center">Hello World!</h2>
<a href="${website}admin/listUser">進入用戶管理界面</a>
<a href="${website}file/fileUpload">上傳單個文件</a>
<a href="${website}file/multiFileUpload">上傳多個文件</a>
<%--<a href="${website}file/fileDownload">下載文件</a>--%>
<a href="${website}file/download">下載指定文件</a>

</body>
</html>

這裏寫圖片描述

6.FileController

    /**
     * 去文件上傳頁面
     *
     * @return
     */
    @RequestMapping(value = "fileUpload", method = RequestMethod.GET)
    public String toFileUpload(){
        return "/file/fileUpload";
    }

    /**
     * 單個文件上傳
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public String fileUpload(@RequestParam("file")MultipartFile file){
        if (!file.isEmpty()){
            try {
                //存入F:\temp目錄下
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File("F:\\temp",
                        System.currentTimeMillis()+ file.getOriginalFilename()));
            } catch (IOException e){
                e.printStackTrace();
            }
        }
        //上傳成功,跳轉至success頁面
        return "file/success";
    }

這裏寫圖片描述

7.多個文件上傳

    /**
     * 去多個文件上傳頁面
     *
     * @return
     */
    @RequestMapping(value = "multiFileUpload", method = RequestMethod.GET)
    public String toMultiFileUpload(){
        return "/file/multiFileUpload";
    }

    /**
     * 多個文件上傳
     *
     * @param multiRequest
     * @return
     */
    @RequestMapping(value = "multiUpload", method = RequestMethod.POST)
    public String multiFileUpload(MultipartHttpServletRequest multiRequest) throws IOException {
        Iterator<String> filesNames = multiRequest.getFileNames(); //獲得所有的文件名
        while(filesNames.hasNext()){    //迭代,對單個文件進行操作
            String fileName =filesNames.next();
            MultipartFile file =  multiRequest.getFile(fileName);
            if(!file.isEmpty()){
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File("F:\\temp",
                        System.currentTimeMillis()+ file.getOriginalFilename()));
            }

        }
        //上傳成功,跳轉至success頁面
        return "file/success";
    }

這裏寫圖片描述

二、文件下載

1.index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2 align="center">Hello World!</h2>
<a href="${website}admin/listUser">進入用戶管理界面</a>
<a href="${website}file/fileUpload">上傳文件</a>
<%--<a href="${website}file/fileDownload">下載文件</a>--%>
<a href="${website}file/download">下載指定文件</a>

</body>
</html>

2.FileController

現在實現的功能是點擊“下載指定文件”則下載在controller中指定好的文件,還沒有實現把上傳的文件傳入數據庫,也沒實現下載數據庫中要存的文件,日後慢慢改進。

    /**
     * 指定文件下載
     *
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "download",produces = "application/octet-stream;charset=UTF-8")
    public ResponseEntity<byte[]> download() throws IOException {
//                指定文件,必須是絕對路徑
        File file = new File("F:\\temp\\1513489657107psb.jpg");
//                下載瀏覽器響應的那個文件名
        String dfileName = "1.jpg";
//                下面開始設置HttpHeaders,使得瀏覽器響應下載
        HttpHeaders headers = new HttpHeaders();
//                設置響應方式
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//                設置響應文件
        headers.setContentDispositionFormData("attachment", dfileName);
//                把文件以二進制形式寫回
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

效果
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章