Your Ad Here
首页 | 编程语言 | 网站建设 | 游戏天堂 | 冲浪宝典 | 网络安全 | 操作系统 | 软件时空 | 硬件指南 | 病毒相关 | IT 认证
软讯网络 > 编程语言 > Java > 自己写的一个JSP上传文件和下载文件的JavaBean
【标  题】:自己写的一个JSP上传文件和下载文件的JavaBean
【关键字】:JSP,JavaBean
【来  源】:http://blog.csdn.net/tangl_99/archive/2006/04/16/665840.aspx

自己写的一个JSP上传文件和下载文件的JavaBean

Your Ad Here

  这个周末终于可以好好锻炼一下我的IBM ThinkPad T43了。今天看了一些关于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 要上传的文件在表单中的参数名
     * @param fileName String 保存在服务器上的文件名
     * @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,结尾处将多2个字节
     * @param name String 文件上传参数的名字
     * @param is InputStream 服务器对话的输入流
     * @return byte[] 返回获取的文件的buffer,结尾处将多2个字节
     * @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" >的输入按钮。这样,浏览器才会将要上传的文件递交给服务器。 其中name="fileUpload"的名字,就是RunnningUpLoader.doUpload函数中的name参数。

使用的时候直接用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");//设置为下载application/x-download
     System.out.println(this.getClass().getClassLoader().getResource("/").getPath());
     String filenamedownload = filePath;
     String filenamedisplay = fileName;//系统解决方案.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");
    }

 

 

免费的portal平台,商业级的中间件产品:【上一篇】
J2EE应用程序异常处理框架:【下一篇】
【相关文章】
  • tomcat下的jsp和servlet的字符编码问题
  • Servlet/JSP服务器端的重定向 摘抄
  • JSP开发中常用技巧
  • 使用jsp/el做网站怎么样?
  • Jsp生成静态页面
  • [转载]jsp+tomcat+mysql&sevlet&javabean配置全过程
  • JSP 如何连接 DB2 数据库
  • jsp+javascrip 动态构造树
  • 以开源精神看Php和Jsp/Java
  • 用eclipse + wtp 开发JSP
  • 【随机文章】
  • Win32调试API 第二部分
  • shell 13问总汇
  • SAP大中国区执行副总裁黄骁俭谈中小企业的企业级信息化
  • 浅谈关于redo log file的故障处理
  • jsp在线考试系统-been文件(1)
  • 軟件和ERP,GIS,OA,MIS,EMIS的關系
  • shell问答16:批量修改文件名后缀
  • 提供一个可以在windows下查看linux系统文件的工具
  • SQL Server2000测试题
  • Liechtenstein
  • 【相关评论】
    没有相关评论
    【发表评论】
    姓名:
    邮件:
    随机码*
    评论*
          
    |  首 页  |  版权声明  |  联系我们   |  网站地图  |
    CopyRight © 2004-2007 bbb软讯网络 All Rigths Reserved.