Servlet4.0 實現上傳和下載

一、servlet文件上傳

1)表單的設置表單的enctype,提交方式必須爲post;
    <form action="up" method="post"  enctype="multipart/form-data">

2)servlet3.0版本以前需要使用第三方的jar包commons-fileupload來實現上傳文件,
     servlet3.0版本自帶了上傳文件的api,無需第三方jar包!!

3) 文件存儲在服務器當前項目的根目錄下的upload文件夾中,
     通過request.getServletContext().getRealPath()獲取服務器的絕對再將上傳的文件。

4)    servlet3.0將上傳的文件保存在Part實例中,可以通過request對象根據上傳的表單控件的name獲取對應的part對象,同時也支持多個文件上傳;
  

5)   通過part對象可直接得到文件的輸入流inputStream,在通過outputStream寫到本地即可!


 6)   可以使UUID來作爲文件名,至於後綴名就需要根據上傳時的文件後綴來獲取了,
     但是part對象裏本身並沒有存儲上傳文件的名稱,我們需要從請求頭信息裏去獲取文件名         瀏覽器發送上傳文件請求時將文件名存儲在Request Head裏的Content-Disposition裏;
     但Content-Disposition得值裏除了文件名信息還有一些其他信息:
     Content-Disposition:form-data; name="file"; filename="test.txt"

 

 二、文件上傳的效果

    2.1) 一個文件上傳:

查看服務器的路徑: E:\myjava\out\artifacts\myservlet_0326_war_exploded\upload 上傳的圖片

JSP頁面 

<form action="up.action" method="post"  enctype="multipart/form-data">
   照片1: <input type="file" name="myfile"><br/>
   說明:  <input type="text" name="content"><br/>
    <input type="submit" value="上傳文件">
</form>

 UploadServlet代碼:

 protected void up(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //System.out.println("save !");
        //輸出對象
        PrintWriter out = response.getWriter();

        //1>上傳的文件保存在Part對象
        Part  part =request.getPart("myfile");


        //2>頭信息文件 form-data; name="myfile"; filename="main.png"
        String desc = part.getHeader("Content-Disposition");
        //out.println(desc);

        //3) 截取圖片的後綴名 .png  .jpg
        String suffix = desc.substring(desc.lastIndexOf("."),desc.length()-1);
       // out.println(suffix);

        //4)隨機的生存一個32的字符串
        //498215e4-ab4a-4ffa-bb99-f0fda7d6d851.jpg
        String fileName = UUID.randomUUID()+suffix;
       // out.println(fileName);

        //5)輸入流對象
        InputStream is = part.getInputStream();

        //6)動態獲取服務器的路徑
        String filePath = request.getServletContext().getRealPath("/upload");
        //文件是否存在
        File file =new File(filePath);
        if(!file.exists()){
            file.mkdirs();   //創建目錄
        }

        //完整的路徑
        String path = filePath +"/"+fileName;

//        7)寫入
        FileOutputStream fos = new FileOutputStream(path);
        byte[] bty = new byte[1024];
        int length =0;
        //文件
        while ((length=is.read(bty))!=-1){
            fos.write(bty,0,length);
        }

        //流關閉
        is.close();
        fos.close();

        ///////////////////////

        out.println();
        //關閉
        out.flush();
        out.close();


    }

 

 

 

2.2) 多個文件上傳:

查看服務器的路徑: E:\myjava\out\artifacts\myservlet_0326_war_exploded\upload 上傳的圖片 

JSP頁面 

<form action="ups.action" method="post"  enctype="multipart/form-data">
   照片1: <input type="file" name="myfile"><br/>
   照片2: <input type="file" name="myfile"><br/>
   照片3: <input type="file" name="myfile"><br/>
    <input type="submit" value="上傳文件">
</form>

 UploadServlet代碼:

    protected void ups(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //集合對象
        List<String> fileNames = new LinkedList<String>();

        //輸出對象
        PrintWriter out = response.getWriter();

        //對象集合
        Collection<Part> parts=request.getParts();

        //遍歷所有的表單內容,將表單中的文件寫入上傳文件目錄
       for (Iterator<Part> iterator=parts.iterator(); iterator.hasNext();){

           //Part對象
           Part part= iterator.next();

           //上傳的文件保存在Part對象
             getFileName(request,part);
       }
        ///////////////////////

        out.println();
        //關閉
        out.flush();
        out.close();


    }

    /**
     * 獲得文件名
     * @param request
     * @param part
     * @throws IOException
     */
    private void getFileName(HttpServletRequest request,Part part) throws IOException {
        //2>頭信息文件 form-data; name="myfile"; filename="main.png"
        String desc = part.getHeader("Content-Disposition");

        //3) 截取圖片的後綴名 .png  .jpg
        String suffix = desc.substring(desc.lastIndexOf("."),desc.length()-1);

        //4)隨機的生存一個32的字符串
        //498215e4-ab4a-4ffa-bb99-f0fda7d6d851.jpg
        String fileName = UUID.randomUUID()+suffix;
        // out.println(fileName);

        //5)輸入流對象
        InputStream is = part.getInputStream();

        //6)動態獲取服務器的路徑
        String filePath = request.getServletContext().getRealPath("/upload");
        //文件是否存在
        File file =new File(filePath);
        if(!file.exists()){
            file.mkdirs();   //創建目錄
        }

        //完整的路徑
        String path = filePath +"/"+fileName;

//        7)寫入
        FileOutputStream fos = new FileOutputStream(path);
        byte[] bty = new byte[1024];
        int length =0;
        //文件
        while ((length=is.read(bty))!=-1){
            fos.write(bty,0,length);
        }

        //流關閉
        is.close();
        fos.close();
    }

三、文件下載的效果

 

JSP頁面

<body>
<a href="down.action?fileName=d88c4317-5aa8-4384-991e-7c1757640fe0.jpg">下載圖片</a>
</body>

UploadServlet 代碼

  protected void down(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

         //請求文件名
        String str =request.getParameter("fileName");

        //服務器路徑(注意必須有這個文件)
        String path = request.getServletContext().getRealPath("/upload")+"/"+str; //默認認爲文件在當前項目的根目錄

        System.out.println(path);

       //輸入流
        FileInputStream fis = new FileInputStream(path);
        //響應頭信息
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment; filename="+str);
       //文件寫入
        ServletOutputStream outs = response.getOutputStream();
        byte[] bt = new byte[1024];
        int length = 0;
        while((length=fis.read(bt))!=-1){
            outs.write(bt,0,length);
        }
        //關閉流
        outs.close();
        fis.close();

    }

注意:  如果是MVN工程,要從服務器上下載圖片時,這個服務器路徑是有權限的,不能訪問:   C:\myjava\mvn_0327\target\mvn_0327\upload\

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