Jsp中實現檔案上傳與下載

來源:互聯網
上載者:User
1.用戶端上傳檔案
    用戶端通過一個Jsp頁面,上傳檔案到伺服器,該Jsp頁面必須含有File類表單,並且表單必須設定enctype="multipart/form- data"。提交表單時通過內建對象request,request.getInputStream();方法獲得一個輸入資料流。
    在上傳檔案時,會有附加資訊,如下所示: -----------------------------7d71042a40328
Content-Disposition: form-data; name="fileforload"; filename="C:/Documents and Settings/ZJ/案頭/book.txt"
Content-Type: text/plain
//此處為檔案內容
-----------------------------7d71042a40328
Content-Disposition: form-data; name="submit" commit
-----------------------------7d71042a40328--     附加資訊大小為297位元組(不確定這個值,測試得到),可通過request.getContentLength()>297來判斷是否上傳了檔案還是提交Null 字元串。 2.測試
    fileupload.jsp負責提交檔案,accept.jsp負責實現上傳功能。
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>     伺服器端得到的上傳檔案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 我喜歡駕馭著代碼在風馳電掣中創造完美;
我喜歡操縱著代碼在隨心所欲中體驗生活;
我喜歡用心情代碼編製我小小的與眾不同;
每一段新的代碼在我手中延生對我來說就象觀看刹那花開的感動;
我不需要焦點.因為我就是焦點! -----------------------------7d75b1540328
Content-Disposition: form-data; name="submit" commit
-----------------------------7d75b1540328--   3.去除附加資訊
    按照HTTP協議,檔案表單提交的資訊中,前4行和後5行是表單本身的資訊,中間部分才是上傳的檔案的內容。下例對上傳的檔案進行處理,擷取檔案名稱,並去除附加資訊。   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>
    (註:如果檔案名稱是中文,會出現亂碼。) 5.檔案下載
    Jsp內建對象response調用方法getOutputStream()可以擷取一個指向客戶的輸出資料流,伺服器將檔案寫入這個流,然後可下載此檔案。 6.測試
    download.jsp顯示下載選項,LoadFile.java(Servlet)負責下載檔案。
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>  
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.