spring專題---第三部分MVC---上傳下載機制

在這裏插入圖片描述

本篇內容總結如下:

    前言
    單文件上傳
    多文件上傳
    下載
    總結
    分享與交流

前言

    上傳文件在我們的項目開發中經常用到,spring MVC爲我們提供了一套很好的上傳下載機制,有效的簡化了開發步驟。

單文件上傳

(1)在pom.xml中引入fileupload組件依賴。它是Apache fileupload組件,spring MVC對其進行了封裝,從而使我們應用的得心應手。

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>

(2)在pom.xml中引入JSTL相關依賴,因爲下邊JSP要用JSTL表達式作判斷。

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

(3)創建JSP頁面,負責前端用戶交互。

<body>
<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="img">
    <input type="submit" value="提交">
</form><br/>
<c:if test="${filePath!=null}">
    <h1>上傳圖片</h1><br/>
    <img  src="${filePath}">
</c:if>
</body>

    •input的type設置爲file
    •form表單的method設置爲post,不能用get請求,因爲get請求只會將文件名傳至後臺
    •form表單的enctype設置爲multipart/form-data,表示以二進制的形式傳輸數據。
    •${filePath},EL表達式,filePath是指後臺返回的值,該值表示文件在後臺的位置,前臺以此位置顯示該文件內容。
(4)完成業務方法,接收前臺發過來的文件,並完成上傳操作。我們使用MultipartFile對象作爲參數。

@Controller
public class upload {

    @RequestMapping(value = "/upload",method = RequestMethod.POST)//method一定要設置爲POST
    public String upload(@RequestParam(value = "img")MultipartFile img, HttpServletRequest request)throws Exception{
        if(img.getSize()>0){//判斷是否有文件傳過來
//            String path=request.getSession().getServletContext().getRealPath("file");

            String path="E:\\idea\\day_project\\spring_mvc2\\src\\main\\webapp\\file";//設置文件上傳後保存的位置
            String fileName=img.getOriginalFilename();//獲得上傳的文件名
            File file=new File(path,fileName);
            img.transferTo(file);
            request.setAttribute("filePath","file/"+fileName);//file+文件名保存在域中,前臺通過它找到文件位置
            return "fileupload";
        }
        return "error";
    }
}

(5)測試
在這裏插入圖片描述
在這裏插入圖片描述

多文件上傳

    多文件上傳在我們的項目開發中也經常用的到,有的時候需要用戶上傳多個文件,我們可以參考單文件上傳案例,並結合集合的思想寫一個多文件上傳的案例。
(1)pom.xml中所需的依賴就不再說明了,可以參考上面案例。
(2)創建JSP頁面,實現與用戶交互。

<body>
<form action="uploads" method="post" enctype="multipart/form-data">
    file1:<input type="file" name="imgs"><br/>
    file2:<input type="file" name="imgs"><br/>
    file3:<input type="file" name="imgs"><br/>
    <input type="submit" value="提交">
</form>
<c:if test="${filePaths!=null}">
<h1>上傳圖片</h1><br/>
<c:forEach items="${filePaths}" var="filePath" >
<img  width="300px" height="180px" src="${filePath}">
    </c:forEach>
</c:if>
</body>

(3)完成業務方法,實現文件上傳。

@Controller
public class upload {

    @RequestMapping(value = "/uploads",method = RequestMethod.POST)//method一定要設置爲POST
    public String uploads(@RequestParam(value = "imgs")MultipartFile[] imgs, HttpServletRequest request)throws Exception{
        List<String> filePaths=new ArrayList<String>();
        for(MultipartFile img:imgs){
            if(img.getSize()>0){//判斷是否有文件傳過來

                String path="E:\\idea\\day_project\\spring_mvc2\\src\\main\\webapp\\file";//設置文件上傳後保存的位置
                String fileName=img.getOriginalFilename();//獲得上傳的文件名
                File file=new File(path,fileName);
                filePaths.add("file/"+fileName);
                img.transferTo(file);
            }
        }
        request.setAttribute("filePaths",filePaths);//前臺通過它找到文件位置
        return "fileupload";
    }
}

(4)測試
在這裏插入圖片描述

下載

    項目中,文件上傳和文件下載通常是共存的,我們在開發中不僅要完成上傳功能,還要實現下載功能,實現後臺文件資源傳至前臺。
(1)在JSP頁面中實現使用超鏈接,下載上邊案例上傳的圖片。

<a href="download?fileName=1.jpg">下載圖片</a>

(2)完成業務方法,實現文件下載。

@Controller
public class upload {

    @RequestMapping("/download")
    public void downloadFile(String fileName, HttpServletRequest request, HttpServletResponse response){
        if (fileName!=null){
            String realPath=request.getServletContext().getRealPath("file/");
            File file=new File(realPath,fileName);
            OutputStream out=null;
            if(file.exists()){
                response.setHeader("Content-Disposition","attachment;filename="+fileName);
                try{
                    out=response.getOutputStream();
                    out.write(FileUtils.readFileToByteArray(file));
                    out.flush();
                }catch(IOException e){
                    e.printStackTrace();
                }finally {
                    if(out!=null){
                        try{
                            out.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
    }
}

(3)測試
在這裏插入圖片描述

總結

    spring MVC對於文件的上傳和下載提供了很好的支持,文件上傳和下載底層都是通過IO流完成的,上傳就是將客戶端的資源通過IO流寫入服務端,下載則是將服務端資源通過IO流寫入客戶端。

分享與交流

    以上是我個人學習記錄總結,如果總結的不到位,還請大佬們不吝賜教。
    如果你在寫項目的時候,遇到一些不尋常的問題,也可以關注我的博客園,上邊會發布一些我在寫項目中遇到的各種問題以及解決方式。

發佈了31 篇原創文章 · 獲贊 30 · 訪問量 6508
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章