服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

用cos进行文件上传


  在jsp中实现文件上传,可用的类库很多,比如有著名的jspsmart公司smartupload,struts里面也有。我这里说说cos,它是o'reilly公司的,o'reilly的图书是很8错的,这个上传的组件也做得很棒,最重要的是,它是open source的。
  
  下载最新的cos包(http://www.servlets.com/cos/index.html),加入到你的classpath中。
  
  编写一个需要上传文件的jsp,为了方便,我就用一个简单的htm文件了,在这个页面中,我们让用户一次可以上传3个文件。
  /////////////////////upload.htm////////////////////////////////////
  <!doctype html public "-//w3c//dtd html 4.01 transitional//en"
  "http://www.w3.org/tr/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="content-type" content="text/html;charset=gb2312">
  <title>无标题文档</title>
  </head>
  
  <body>
  <!-- enctype的值很重要,upload.jsp为处理上传的jsp-->
  <form name="form1" method="post" enctype="multipart/form-data"
  action="upload.jsp">
  <p>
   <input name="file1" type="file">
  </p>
  <p>
   <input name="file2" type="file">
  </p>
  <p> <input name="file3" type="file">
  </p>
  <p>
   <input type="submit" name="submit" value="上传">
  </p>
  </form >
  
  </body>
  </html>
  
  在c:/下建一个目录c:/upload,用来存放上传的文件。
  
  写一个jsp或者servlet来实现上传,我这里用一个叫upload.jsp,这样就不用配置web.xml,呵呵,比较懒的说。
  ////////////////////////////upload.jsp////////////////////////
  
  <%@page import="java.io.*"%>
  <%@page import="com.oreilly.servlet.multipartrequest"%>
  <%@page import="com.oreilly.servlet.multipart.coverfilerenamepolicy"%>
  <%@page contenttype="text/html; charset=gb2312" %>
  <%
  //文件上传后,保存在c://upload
  string savedirectory ="c://upload";
  //每个文件最大5m,最多3个文件,所以...
  int maxpostsize =3 * 5 * 1024 * 1024 ;
  //response的编码为"gb2312",同时采用缺省的文件名冲突解决策略,实现上传
  multipartrequest multi =
      new multipartrequest(request, savedirectory, maxpostsize,
                "gb2312");
  
  //输出反馈信息
   enumeration files = multi.getfilenames();
     while (files.hasmoreelements()) {
      system.err.println("ccc");
      string name = (string)files.nextelement();
      file f = multi.getfile(name);
      if(f!=null){
       string filename = multi.getfilesystemname(name);
       string lastfilename= savedirectory+"//" + filename;
       out.println("上传的文件:"+lastfilename);
       out.println("<hr>");
  
      }
     }
  
  %>
  <meta http-equiv="content-type" content="text/html;charset=gb2312">
  
  最后把这2个文件发布到你的服务器就行了。上传文件就搞定啦,以后你想在你邮件系统里面嵌入发送附件的功能,用这个来做上传也不错啊。

扫描关注微信公众号