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

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-1);
        fos.close();
    }

    /**
     * 获取上传的文件buffer,结尾处将多一个换行符
     * @param name String 文件上传参数的名字
     * @param is InputStream 服务器对话的输入流
     * @return byte[] 返回获取的文件的buffer,结尾处多一个换行符
     * @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()) {
                System.out.println(readStreamLineAsString(bis)); // skip a line
                System.out.println(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;
                System.out.println(new String(lineData,"ASCII"));
                while(!isByteArraystartWith(lineData, lineSeparatorByte)) {
                    lineData = readStreamLine(bis);
                    if(lineData == null)
                        return null;
                    System.out.println(new String(lineData,"ASCII"));
                }
            }
        }
        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 && b != '/n') {
            bos.write(b);
            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");
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值