现在的位置: 首页 > 综合 > 正文

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

2013年12月04日 ⁄ 综合 ⁄ 共 5312字 ⁄ 字号 评论关闭

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");
    }

抱歉!评论已关闭.