天天看點

jsp 檔案下載下傳

1.最直接最簡單的,方式是把檔案位址直接放到html頁面的一個連結中。這樣做的缺點是把檔案在伺服器上的路徑暴露了,并且還無法對檔案下載下傳進行其它的控制(如權限)。這個就不寫示例了。

2.在伺服器端把檔案轉換成輸出流,寫入到response,以response把檔案帶到浏覽器,由浏覽器來提示使用者是否願意儲存檔案到本地。(示例如下)

<%

response.setContentType(fileminitype);

response.setHeader("Location",filename);

response.setHeader("Cache-Control", "max-age=" + cacheTime);

     //filename應該是編碼後的(utf-8)

response.setHeader("Content-Disposition", "attachment; filename=" + filename); 

response.setContentLength(filelength);

OutputStream outputStream = response.getOutputStream();

InputStream inputStream = new FileInputStream(filepath);

byte[] buffer = new byte[1024];

int i = -1;

while ((i = inputStream.read(buffer)) != -1) {

outputStream.write(buffer, 0, i);

}

outputStream.flush();

outputStream.close();

inputStream.close();

outputStream = null;

%>

  3.既然是JSP的話,還有一種方式就是用Applet來實作檔案的下載下傳。不過客戶首先得信任你的這個Applet小程式,由這個程式來接受由servlet發送來的資料流,并寫入到本地。

  servlet端示例

public void service(HttpServletRequest req, HttpServletResponse res)

            throws ServletException, IOException {

        res.setContentType(" text/plain ");

        OutputStream outputStream = null;

        try {

            outputStream = res.getOutputStream();

            //把檔案路徑為srcFile的檔案寫入outputStream中

            popFile(srcFile, outputStream)) ;

        } catch (IOException e) {

            e.printStackTrace();    

     }

          }

JApplet端示例

URLConnection con;

            //url是被調用的SERVLET的網址 如 *.do 

            con = url.openConnection();

con.setUseCaches(false);

            con.setDoInput(true);

            con.setDoOutput(true);

            con.setRequestProperty("Content-Type",

                "application/octet-stream");

            InputStream in = con.getInputStream();

            ProgressMonitorInputStream pmInputStream = new ProgressMonitorInputStream

(pane, "正在從伺服器下載下傳檔案内容", in);

            ProgressMonitor pMonitor = pmInputStream.getProgressMonitor();

            pMonitor.setMillisToDecideToPopup(3);

            pMonitor.setMillisToPopup(3);

            //localfilepath本地路徑,localstr檔案檔案夾,filename本地檔案名

            String localfilepath = localstr + filename ;

            //方法saveFilsaveFilee是把輸入流pmInputStream寫到檔案localfilepath中 

            if(saveFilsaveFilee(localfilepath,pmInputStream)){

            openLocalFile(localfilepath);

                  }

  4.順便把JApplet上傳檔案的代碼也貼上來.

            //url是被調用的SERVLET的網址 如 *.do         

          con.setUseCaches(false);

            con.setRequestProperty("Content-Type","application/octet-stream"); 

OutputStream out = con.getOutputStream();

            String localfilepath = localstr + filename;

            //檔案getOutputStream是把檔案localfilepath寫到輸出流out中

            getOutputStream(localfilepath,out);

            return true;

        }catch (IOException e) {

               System.out.println("檔案上傳出錯!");

            e.printStackTrace();

              }

  servlet端代碼示例

           throws ServletException, IOException {

        InputStream inputStream = null;

            inputStream = res.getInputStream();

//把輸入流inputStream儲存到檔案路徑為srcFile的檔案中

            writefile(srcFile, inputStream);

        }

          } // end service

  總結:在檔案的傳輸中是流的形式存在的,在硬碟上是檔案的形式存在的。我們要做的隻是通過HttpServletRequest和HttpServletResponse,或者是response和request來發送流和讀取流。以及把檔案轉換成流或把流轉換成檔案的操作。

亂碼處理的檔案下載下傳:

原創:

<%@ page language="java" pageEncoding="UTF-8"%>

< import="java.io.*" %>

< import="java.net.URLEncoder"%>

request.setCharacterEncoding("gb2312");

response.setCharacterEncoding("gb2312");

String filename="圖檔.jpg";

String filepath="e:/圖檔.jpg";

if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0)

    filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");//firefox浏覽器

else 

     if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0)

          filename = URLEncoder.encode(filename, "UTF-8");//IE浏覽器

response.setContentType("text/plain");

response.reset();

response.setHeader("Cache-Control", "max-age=0" );

response.setHeader("Content-Disposition", "attachment; filename=" + filename);

/*如果有換行,對于文本檔案沒有什麼問題,但是對于其它格

式,比如AutoCAD、Word、Excel等檔案下載下傳下來的檔案中就會多出一些換行符//0x0d和0x0a,這樣可能導緻某些格式的檔案無法打開,有些也可以正常打開。同//時response.reset()這種方式也能清空緩沖區, 防止頁面中的空行等輸出到下載下傳内容裡去*/

//下載下傳時抛出異常

out.clear();

out=pageContext.pushBody();