Linux中国 Linux中国门户站!
设为主页 设为主页
收藏本站 收藏本站
 
当前位置 :首页 ->编程语言 ->JAVA/JSP教程 ->正文

JSP文件下载的几种方式

来源:Linuxdby.com 作者:Webmaster 时间:2007-04-28 点击: [收藏] [投稿]
1。最直接最简单的,方式是把文件地址直接放到html页面的一个链接中。这样做的缺点是把文件在服务器上的路径暴露了,并且还无法对文件下载进行其它的控制(如权限)。这个就不写示例了。
2。在服务器端把文件转换成输出流,写入到response,以response把文件带到浏览器,由浏览器来提示用户是否愿意保存文件到本地。(示例如下)
<%
 response.setContentType(fileminitype);
 response.setHeader("Location",filename);
 response.setHeader("Cache-Control", "max-age=" + cacheTime);
 response.setHeader("Content-Disposition", "attachment; filename=" + filename); //filename应该是编码后的(utf-8)
 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();
            popFile(srcFile, outputStream)) ;//把文件路径为srcFile的文件写入到outputStream中。
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
JApplet端示例
   URLConnection con;
        try {
            con = url.openConnection();//url是被调用的SERVLET的网址 如http://localhost:8080/sendDateSevlet.do 
            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);
            String localfilepath = localstr + filename ;//localfilepath本地路径,localstr文件文件夹,filename本地文件名
     if(saveFilsaveFilee(localfilepath,pmInputStream)){ //方法saveFilsaveFilee是把输入流pmInputStream写到文件localfilepath中。                   

     openLocalFile(localfilepath);
            }


4。顺便把JApplet上传文件的代码也贴上来.
JApplet端示例

URLConnection con;
        try {
            con = url.openConnection();//url是被调用的SERVLET的网址 如http://localhost:8080/sendDateSevlet.do        
     con.setUseCaches(false);
            con.setDoInput(true);

 如果您对本文有任何疑问或者建议,请到讨论区发表您的意见: >> 论坛入口 <<



上一篇:jsp连接数据库oracle   下一篇:JSP中可能会碰到的问题解答

文章评论】 【收藏本文】 【推荐好友】 【打印本文】 【我要投稿】 【论坛讨论
更多相关文章
Power by linux-cn.com 粤ICP备05006655号