小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

自己寫的一個JSP上傳文件和下載文件的JavaBean...

 加菲 2006-04-17

  這個周末終于可以好好鍛煉一下我的IBM ThinkPad T43了。今天看了一些關(guān)于JSP,Servlet方面的資料,寫了簡單的兩個JavaBean。一個是UpLoad,一個是DownLoad。寫得很簡單,沒有使用其它任何組件,自己做的。大家可以來看看。

1.RunningUpLoader上傳Bean

  首先是RunningUpLoader.java,代碼有些多,因為我是自己來解析輸入流的。

package testupload;
import java.io.*;
import javax.servlet.http.HttpServletRequest;


public class RunningUpLoader {
    public RunningUpLoader() {
    }

    /**
     * 上傳文件
     * @param request HttpServletRequest Servlet的請求對象
     * @param name String 要上傳的文件在表單中的參數(shù)名
     * @param fileName String 保存在服務(wù)器上的文件名
     * @throws IOException
     */
    public void doUpload(HttpServletRequest request, String name,String fileName) throws
            IOException {
        InputStream in = request.getInputStream();
        byte[] buffer = getFileContent(name,in);
        FileOutputStream fos = new FileOutputStream(fileName);
        fos.write(buffer,0,buffer.length-2);
        fos.close();
    }

    /**
     * 獲取上傳的文件buffer,結(jié)尾處將多2個字節(jié)
     * @param name String 文件上傳參數(shù)的名字
     * @param is InputStream 服務(wù)器對話的輸入流
     * @return byte[] 返回獲取的文件的buffer,結(jié)尾處將多2個字節(jié)
     * @throws IOException
     */
    private byte[] getFileContent(String name, InputStream is) throws IOException{
        int index;
        boolean isEnd = false;
        byte[] lineSeparatorByte;
        byte[] lineData;
        String content_disposition;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        lineSeparatorByte = readStreamLine(bis);
        while(!isEnd) {
            lineData = readStreamLine(bis);
            if(lineData == null) {
                break;
            }
            content_disposition = new String(lineData,"ASCII");
            index = content_disposition.indexOf("name=\"" + name + "\"");
            if (index >= 0 && index < content_disposition.length()) {
                readStreamLineAsString(bis); // skip a line
                readStreamLineAsString(bis); // skip a line

                while ((lineData = readStreamLine(bis)) != null) {
                    System.out.println(new String(lineData));
                    if (isByteArraystartWith(lineData, lineSeparatorByte)) { // end
                        isEnd = true;
                        break;
                    } else {
                        bos.write(lineData);
                    }
                }
            }else {
                lineData = readStreamLine(bis);
                if(lineData == null)
                    return null;
                while(!isByteArraystartWith(lineData, lineSeparatorByte)) {
                    lineData = readStreamLine(bis);
                    if(lineData == null)
                        return null;
                }
            }
        }
        return bos.toByteArray();
    }

    private byte[] readStreamLine(BufferedInputStream in) throws IOException{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int b = in.read();
        if(b== -1)
            return null;
        while(b != -1) {
            bos.write(b);
            if(b == ‘\n‘) break;
            b = in.read();
        }
        return bos.toByteArray();
    }

    private String readStreamLineAsString(BufferedInputStream in) throws IOException {
        return new String(readStreamLine(in),"ASCII");
    }

    private boolean isByteArraystartWith(byte[] arr,byte[] pat) {
        int i;
        if(arr == null || pat == null)
            return false;
        if(arr.length < pat.length)
            return false;
        for(i=0;i<pat.length;i++) {
            if(arr[i] != pat[i])
                return false;
        }
        return true;
    }
}


上傳文件文件的時候,需要在之前的html中增加一個form表單,里面需要有個<input type="file" name="fileUpload" >的輸入按鈕。這樣,瀏覽器才會將要上傳的文件遞交給服務(wù)器。 其中name="fileUpload"的名字,就是RunnningUpLoader.doUpload函數(shù)中的name參數(shù)。

使用的時候直接用bean就OK了。比如upload.jsp如下:

<jsp:useBean id="upBean" scope="page" class="testupload.RunningUpLoader" />

<%

upBean.doUpload(request,"fileupload","runningUpLoad.txt");

%>

 

2. RunningDownLoader下載Bean

package testupload;
import java.io.*;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

public class RunningDownLoader {
    public RunningDownLoader() {
    }

    public void doDownload(HttpServletResponse response, String filePath,String fileName) throws
            IOException {
        response.reset();//可以加也可以不加
     response.setContentType("application/x-download");//設(shè)置為下載application/x-download
     System.out.println(this.getClass().getClassLoader().getResource("/").getPath());
     String filenamedownload = filePath;
     String filenamedisplay = fileName;//系統(tǒng)解決方案.txt
     filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
     response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);

     OutputStream output = null;
     FileInputStream fis = null;
     try
     {
         output  = response.getOutputStream();
         fis = new FileInputStream(filenamedownload);

         byte[] b = new byte[1024];
         int i = 0;

         while((i = fis.read(b)) > 0)
         {
             output.write(b, 0, i);
         }
         output.flush();
     }
     catch(Exception e)
     {
         System.out.println("Error!");
         e.printStackTrace();
     }
     finally
     {
         if(fis != null)
         {
             fis.close();
             fis = null;
         }
         if(output != null)
         {
             output.close();
             output = null;
         }
     }

    }

 

}
 

  下載文件,最好是做到Servlet上。直接在Servlet的doGet下面增加如下代碼即可

//Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        RunningDownLoader downloader= new RunningDownLoader();
        downloader.doDownload(response,"E:\\MyProjects\\testupload.rar","upload.bin");
    }

 

 

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多