自己写的一个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-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");
    }

 

 
阅读更多
个人分类: java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭