<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    隨筆-9  評論-168  文章-266  trackbacks-0

     

    Jsp中實現(xiàn)文件上傳與下載  

    1.客戶端上傳文件
       
    客戶端通過一個Jsp頁面,上傳文件到服務(wù)器,該Jsp頁面必須含有File類表單,并且表單必須設(shè)置enctype="multipart/form- data"。提交表單時通過內(nèi)置對象request,request.getInputStream();方法獲得一個輸入流。
        在上傳文件時,會有附加信息,如下所示:

    -----------------------------7d71042a40328
    Content-Disposition: form-data; name="fileforload"; filename="C:"Documents and Settings"ZJ"
    桌面"book.txt"
    Content-Type: text/plain
    //此處為文件內(nèi)容
    -----------------------------7d71042a40328
    Content-Disposition: form-data; name="submit"

    commit
    -----------------------------7d71042a40328--

        附加信息大小為297字節(jié)(不確定這個值,測試得到),可通過request.getContentLength()>297來判斷是否上傳了文件還是提交空字符串。

    2.測試
        fileupload.jsp
    負(fù)責(zé)提交文件,accept.jsp負(fù)責(zé)實現(xiàn)上傳功能。
    fileupload.jsp

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>This page for FileUpload</title>
    </head>
    <body>
    <p>Choose the file for uploading:
    <form action="accept.jsp" method=post enctype="multipart/form-data">
      <input type=file name=fileforload size=30>
      <br>
      <input type=submit value=commit name=submit>
    </form>
    </body>
    </html>

    accept.jsp

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>This page for response</title>
    </head>
    <body>
    <%try{
     if(request.getContentLength()>297){
       InputStream in=request.getInputStream();
       File f=new File("d:/temp","test.txt");
       FileOutputStream o=new FileOutputStream(f);
       byte b[]=new byte[1024];
       int n;
       while((n=in.read(b))!=-1){
      o.write(b,0,n);
       }
       o.close();
       in.close();
       out.print("File upload success!");
     }
     else{
      out.print("No file!");
     }
    }
    catch(IOException e){
     out.print("upload error.");
     e.printStackTrace();
    }
    %>
    </body>
    </html>

        服務(wù)器端得到的上傳文件I like.txt,取名為test.txt

    -----------------------------7d75b1540328
    Content-Disposition: form-data; name="fileforload"; filename="C:"Documents and Settings"ZJ"
    桌面"I like.txt"
    Content-Type: text/plain

    我喜歡駕馭著代碼在風(fēng)馳電掣中創(chuàng)造完美;
    我喜歡操縱著代碼在隨心所欲中體驗生活;
    我喜歡用心情代碼編制我小小的與眾不同;
    每一段新的代碼在我手中延生對我來說就象觀看剎那花開的感動;
    我不需要焦點.因為我就是焦點!

    -----------------------------7d75b1540328
    Content-Disposition: form-data; name="submit"

    commit
    -----------------------------7d75b1540328--

    3.去除附加信息
       
    按照HTTP協(xié)議,文件表單提交的信息中,前4行(不足的自動空行)和后5行是表單本身的信息,中間部分才是上傳的文件的內(nèi)容。下例對上傳的文件進行處理,獲取文件名,并去除附加信息。

    4.測試
        fileupload.jsp
    不變,accept.jsp修改如下:

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>The real file</title>
    </head>
    <body>
    <%try{
     //use sessionid to create a temp file.
     String tempFileName=(String)session.getId();
     //create the temp file.
     File temp=new File("d:/temp",tempFileName);
     FileOutputStream o=new FileOutputStream(temp);
     if(request.getContentLength()>297){
       //write the upload content to the temp file.
       InputStream in=request.getInputStream();
       byte b[]=new byte[1024];
       int n;
       while((n=in.read(b))!=-1){
        o.write(b,0,n);
       }
       o.close();
       in.close();
       //read the temp file.
       RandomAccessFile random=new RandomAccessFile(temp,"r");
       //read Line2 to find the name of the upload file.
       int second=1;
       String secondLine=null;
       while(second<=2){
        secondLine=random.readLine();
        second++;
       }
       //get the last location of the dir char.'""'.
       int position=secondLine.lastIndexOf('""');
       //get the name of the upload file.
       String fileName=secondLine.substring(position+1,secondLine.length()-1);
       //relocate to the head of file.
       random.seek(0);
       //get the location of the char.'Enter' in Line4.
       long forthEndPosition=0;
       int forth=1;
       while((n=random.readByte())!=-1&&(forth<=4)){
        if(n=='"n'){
         forthEndPosition=random.getFilePointer();
         forth++;
        }
       }
       File realFile=new File("d:/temp",fileName);
       RandomAccessFile random2=new RandomAccessFile(realFile,"rw");
       //locate the end position of the content.Count backwards 6 lines.
       random.seek(random.length());
       long endPosition=random.getFilePointer();
       long mark=endPosition;
       int j=1;
       while((mark>=0)&&(j<=6)){
        mark--;
        random.seek(mark);
        n=random.readByte();
        if(n=='"n'){
         endPosition=random.getFilePointer();
         j++;
        }
       }
       //locate to the begin of content.Count for 4 lines's end position.
       random.seek(forthEndPosition);
       long startPoint=random.getFilePointer();
       //read the real content and write it to the realFile.
       while(startPoint<endPosition-1){
        n=random.readByte();
        random2.write(n);
        startPoint=random.getFilePointer();
       }
       random2.close();
       random.close();
       //delete the temp file.
       temp.delete();
       out.print("File upload success!");
     }
     else{
      out.print("No file!");
     }
    }
    catch(IOException e){
     out.print("upload error.");
     e.printStackTrace();
    }
    %>
    </body>
    </html>

        (注:如果文件名是中文,會出現(xiàn)亂碼。)

    5.文件下載
        Jsp
    內(nèi)置對象response調(diào)用方法getOutputStream()可以獲取一個指向客戶的輸出流,服務(wù)器將文件寫入這個流,然后可下載此文件。

    6.測試
        download.jsp
    顯示下載選項,LoadFile.java(Servlet)負(fù)責(zé)下載文件。
    download.jsp

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>download page</title>
    </head>
    <body>
    <a href=loadFile>Download:test.zip</a>
    </body>
    </html>

    LoadFile.java

    package com.zj.sample;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.OutputStream;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    @SuppressWarnings("serial")
    public class LoadFile extends HttpServlet{
     public void doGet(HttpServletRequest request,HttpServletResponse response)
       throws IOException,ServletException{
        OutputStream o=response.getOutputStream();
        byte b[]=new byte[1024];
        //the file to download.
        File fileLoad=new File("d:/temp","test.rar");
        //the dialogbox of download file.
        response.setHeader("Content-disposition",
          "attachment;filename="+"test.rar");
        //set the MIME type.
        response.setContentType("application/x-tar");
        //get the file length.
        long fileLength=fileLoad.length();
        String length=String.valueOf(fileLength);
        response.setHeader("Content_Length",length);
        //download the file.
        FileInputStream in=new FileInputStream(fileLoad);
        int n=0;
        while((n=in.read(b))!=-1){
         o.write(b,0,n);
        }
     }
     public void doPost(HttpServletRequest request,HttpServletResponse response)
     throws IOException,ServletException{
      doGet(request,response);
     }

    }

    web.xml(注冊servlet)

    <servlet>
      <servlet-name>LoadFileServlet</servlet-name>
      <servlet-class>com.zj.sample.LoadFile</servlet-class>
    </servlet>
    <servlet-mapping>
      <servlet-name>LoadFileServlet</servlet-name>
      <url-pattern>/loadFile</url-pattern>
    </servlet-mapping>


                                                                                     轉(zhuǎn)自--h(huán)ttp://blog.csdn.net/lookthesea/archive/2007/05/20/1617633.aspx
    posted on 2010-01-03 16:54 紫蝶∏飛揚↗ 閱讀(2880) 評論(2)  編輯  收藏 所屬分類: JSP

    評論:
    # re: [轉(zhuǎn)]Jsp中實現(xiàn)文件上傳與下載 2011-04-07 21:35 | xin_ny
    我要上傳圖片,怎么寫啊!!!  回復(fù)  更多評論
      
    # re: [轉(zhuǎn)]Jsp中實現(xiàn)文件上傳與下載 2014-06-12 11:27 | 小止
    我 request.getInputStream 取到有值,但是存入文件就成0字節(jié)了  回復(fù)  更多評論
      
    主站蜘蛛池模板: 黄色片免费在线观看| 亚洲Av永久无码精品黑人 | 色偷偷亚洲男人天堂| 黄网址在线永久免费观看| 99热亚洲色精品国产88| 国产免费不卡v片在线观看| 亚洲二区在线视频| 性一交一乱一视频免费看| 亚洲va成无码人在线观看| xx视频在线永久免费观看| 国产99在线|亚洲| www.黄色免费网站| 亚洲AV无码一区二区三区网址| 成人毛片免费在线观看| 国产亚洲精品仙踪林在线播放| 亚洲AⅤ无码一区二区三区在线| 91麻豆最新在线人成免费观看| 亚洲人成毛片线播放| 在线播放免费播放av片| 羞羞漫画页面免费入口欢迎你| 色欲国产麻豆一精品一AV一免费| 久久亚洲免费视频| 很黄很黄的网站免费的| 亚洲精品无码久久久久秋霞| 免费一级做a爰片久久毛片潮喷| 无遮挡国产高潮视频免费观看| 无码国产精品久久一区免费| 亚洲人成欧美中文字幕| 亚洲人成网站18禁止一区| 久久精品国产大片免费观看| 国产91在线|亚洲| 亚洲无码视频在线| 中文字幕天天躁日日躁狠狠躁免费| 国产成人亚洲合集青青草原精品 | 亚洲国产另类久久久精品| 99久久国产热无码精品免费| 无码亚洲成a人在线观看| 国内精品99亚洲免费高清| 日本免费人成在线网站| 黄床大片30分钟免费看| 精品亚洲麻豆1区2区3区|