下载:
package learn.load;/**
 * Title:        学习servlet
 * Description:
 * Copyright:    Copyright (c) 2002
 * Company:      
 * @author
 * @version 1.0
 */
import java.io.*;
public class FileDownLoad {  public FileDownLoad() {
  }
  public void fileDown(String aFileName,javax.servlet.http.HttpServletResponse response) throws Exception {
    java.io.BufferedInputStream iin;
    BufferedOutputStream dout;
    try {
       File ff=new File(aFileName);
       if(!ff.exists()){
         throw new Exception("对不起! 您下载的文件不存在");
       }else{
         byte[] buffer;
         int length=(new Long(ff.length())).intValue();
         buffer=new byte[length];
         try{
             iin=new BufferedInputStream(new java.io.FileInputStream(ff));
              //设置类型和头信息
            response.setContentType( "application/octet-stream" ); // MIME type for pdf doc
            int pos=aFileName.lastIndexOf("\\");
            aFileName=aFileName.substring(pos+1);
            pos=aFileName.lastIndexOf(".");
            aFileName="download"+aFileName.substring(pos);
            response.setHeader("Content-disposition", "attachment; filename=" +aFileName);
           //传送数据
            dout = new BufferedOutputStream( response.getOutputStream());
            int once = 0;
            int total = 0;
            while ((total<length) && (once>=0)) {
               once = iin.read(buffer,total,length);
               total += once;
               dout.write(buffer,0,length);
            }
            if(iin!=null){   iin.close();}
            if(dout!=null){  dout.close();}
          }catch(Exception ex){
             throw new Exception("文件下载过程中出现错误! ");
          }
        }
      }catch(Exception ex) {
         throw new Exception("文件下载过程中出现错误! ");
      }
   }
}
JSP页面:
<%@ page contentType="text/html; charset=GBK" %>
<html>
<head>
<title>
fileDownLoad
</title>
</head>
<jsp:useBean id="fload" scope="page" class="learn.load.FileDownLoad" />
<body>
<%
String filename=request.getParameter("filename");
if(filename!=null)  fload.fileDown(filename,response);
%>
<form name=fileload method=post action="fileDownLoad.jsp">
文件名:<input type="file" name="filename"><br>
<input type="submit" name="submit" value="下载">
</form>
</body>
</html>

解决方案 »

  1.   

    这也要呀.......为什么不要bean的呀?
      

  2.   

    上载:
    public void uploadFile(javax.servlet.http.HttpServletRequest req) throws IOException,Exception {
         try {
            String contentType=req.getContentType();
            int contentLength=req.getContentLength();
            java.io.DataInputStream bis=new java.io.DataInputStream(req.getInputStream());
            int once = 0;
            int total = 0;
            byte[] buffer=new byte[contentLength];
            while ((total<contentLength) && (once>=0)) {
              once = bis.read(buffer,total,contentLength);
              total += once;
            }
            int boundaryStart=contentType.indexOf("boundary=");
            boundaryStart=boundaryStart+"boundary=".length();
            String boundary="--"+contentType.substring(boundaryStart);
            int pos=getFormNameIndex(buffer,"filename=\"".getBytes(),1)+"filename=\"".length();
            int posEnd=getFormNameIndex(buffer,"\"".getBytes(),pos);
            String filename=new String(buffer,pos,posEnd-pos);
            pos=filename.lastIndexOf(".");
            String filenames=System.currentTimeMillis()/1000+filename.substring(pos);
            pos=getFormNameIndex(buffer,"Content-Type: ".getBytes(),1);
            pos=getFormNameIndex(buffer,"\r\n".getBytes(),pos+1)+4;
            int endpos=getFormNameIndex(buffer,boundary.getBytes(),pos+20);
            int len=endpos-pos;
            java.io.DataOutputStream bos= new java.io.DataOutputStream(new java.io.FileOutputStream(new java.io.File(filepath,filenames)));
            bos.write(buffer,pos,len);
            bis.close();
            bos.close();
         }catch(Exception exc) {
            throw new Exception("upload failed.");
         }finally{     }
      }
      private int getFormNameIndex(byte[] source,byte[] formname,int start) {
          int soulen=source.length;
          int sealen=formname.length;
          boolean hasSearch=false;
          int pos=-1;
          for(int i=start;i<soulen;i++) {
            if(source[i]==formname[0]) {
              boolean hasSear=true;
              for(int k=1;k<sealen;k++) {
                  if(source[i+k]!=formname[k]) {
                     hasSear=false;
                     break;
                   }
              }
              hasSearch=hasSear;
            }
            if(hasSearch) {
              pos=i;
              break;
            }
          }
         return pos;
      }
    JSP页面:
    <%@ page contentType="text/html; charset=GBK" %>
    <html>
    <head>
    <title>
    fileUpLoad
    </title>
    </head>
    <body>
    <form name=fileload method=post action="fileUpLoadOp.jsp">
    文件名:<input type="file" name="filename"><br>
    文件夹:<input type="checkbox" name="uploadfolder" value="1">
    <input type="submit" name="submit" value="上载">
    </form>
    </body>
    </html>
    JSP处理页面:
    <jsp:useBean id="fload" scope="page" class="learn.load.fileLoad" />
    <%
      fload.uploadFile(request);
    %>
      

  3.   

    去下载个JSPSMARTUPLOAD吧,很好用的,不过没有源码
      

  4.   

    java.io.DataOutputStream bos= new java.io.DataOutputStream(new java.io.FileOutputStream(new java.io.File(filepath,filenames)));
    出错了,在编译的时候显示错误cannot resolve symbol
      

  5.   

    呵呵,bean很简单呀,放在指定的文件夹里不就完了?
      

  6.   

    呜,我被欺骗了,搞不定阿,我将程序改为
    import java.io.*;
    public class fileLoad {
      public fileLoad() {
      }
    public void uploadFile(javax.servlet.http.HttpServletRequest req) throws IOException,Exception {
         try {
            String contentType=req.getContentType();
            int contentLength=req.getContentLength();
            java.io.DataInputStream bis=new java.io.DataInputStream(req.getInputStream());
            int once = 0;
            int total = 0;
            byte[] buffer=new byte[contentLength];
            while ((total<contentLength) && (once>=0)) {
              once = bis.read(buffer,total,contentLength);
              total += once;
            }
            int boundaryStart=contentType.indexOf("boundary=");
            boundaryStart=boundaryStart+"boundary=".length();
            String boundary="--"+contentType.substring(boundaryStart);
            int pos=getFormNameIndex(buffer,"filename=\"".getBytes(),1)+"filename=\"".length();
            int posEnd=getFormNameIndex(buffer,"\"".getBytes(),pos);
            String filename=new String(buffer,pos,posEnd-pos);
            pos=filename.lastIndexOf(".");
            String filenames=System.currentTimeMillis()/1000+filename.substring(pos);
            pos=getFormNameIndex(buffer,"Content-Type: ".getBytes(),1);
            pos=getFormNameIndex(buffer,"\r\n".getBytes(),pos+1)+4;
            int endpos=getFormNameIndex(buffer,boundary.getBytes(),pos+20);
            int len=endpos-pos;
            java.io.DataOutputStream bos= new java.io.DataOutputStream(new java.io.FileOutputStream(new java.io.File(filename,filenames)));        
    bos.write(buffer,pos,len);
            bis.close();
            bos.close();
         }catch(Exception exc) {
            throw new Exception("upload failed.");
         }finally{     }
      }
      private int getFormNameIndex(byte[] source,byte[] formname,int start) {
          int soulen=source.length;
          int sealen=formname.length;
          boolean hasSearch=false;
          int pos=-1;
          for(int i=start;i<soulen;i++) {
            if(source[i]==formname[0]) {
              boolean hasSear=true;
              for(int k=1;k<sealen;k++) {
                  if(source[i+k]!=formname[k]) {
                     hasSear=false;
                     break;
                   }
              }
              hasSearch=hasSear;
            }
            if(hasSearch) {
              pos=i;
              break;
            }
          }
         return pos;
      }
    }
    然后编译,但是它说 Unable to compile class for JSPNote: sun.tools.javac.Main has been deprecated.
    error: File D:\tomcat\webapps\examples\WEB-INF\classes\learn\load\fileLoad.class does not contain type learn.load.fileLoad as expected, but type fileLoad. Please remove the file, or make sure it appears in the correct subdirectory of the class path.气坏我了
      

  7.   

    还是错误!!
    type Exception reportmessage description The server encountered an internal error () that prevented it from fulfilling this request.exception javax.servlet.ServletException: upload failed.
    at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:471)
    at org.apache.jsp.fileUpLoadOp$jsp._jspService(fileUpLoadOp$jsp.java:94)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:201)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:381)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:473)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:260)
    at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:646)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:483)
    at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:646)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:483)
    at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
    at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2349)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
    at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:646)
    at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
    at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:644)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:171)
    at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:644)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:483)
    at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
    at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:646)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:469)
    at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:644)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:483)
    at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
    at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:405)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:376)
    at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:508)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:518)
    at java.lang.Thread.run(Thread.java:536)