SmartUpload组件控制文件上传

HTML:

  <form action="upload/doUpload.jsp" method="post" enctype="multipart/form-data">
   <input type="file" name="myfile"/><br />
   <input type="file" name="myfile2" /><br />
   描述:<input type="text" name="desc" /><br />
   <input type="submit"/>
   </form>
form表单属性必须定义method="post" enctype="multipart/form-data"

JSP:

<%@page import="com.jspsmart.upload.SmartUpload"%>
<%@page import="com.jspsmart.upload.File"%>
 <%
     SmartUpload su = new SmartUpload();
     //初始化
     su.initialize(pageContext); //内置对象pageContext作为参数
     String allowed="jpg,bmp,txt";
     su.setAllowedFilesList(allowed); //设置允许上传的扩展名
     String unallowed="bat";
     su.setDeniedFilesList(unallowed); //不允许上传
     su.setMaxFileSize(1024*1024*2);  //最大上传2M
     try{
      su.upload(); //上传到内存
      for (int i = 0; i < su.getFiles().getCount(); i++) { //多个上传
       File file = su.getFiles().getFile(i); //取得单个文件上传信息
       if(file.isMissing()) //判断是否为空上传项
        continue;
      String desc = su.getRequest().getParameter("desc"); //在upload()方法之后才可使用,获取表单信息
      out.print("上传描述:"+desc);
      File file = su.getFiles().getFile(i); //取得单个文件上传信息
      String filePath = "file/"; 
      filePath += file.getFileName(); //设置文件在服务器保存位置
      file.saveAs(filePath,SmartUpload.SAVE_VIRTUAL); //文件另存到tomcat部署的项目文件夹中,不是当前项目物理位置
      //如果保存绝对路径,
      //file.saveAs(filePath,SmartUpload.SAVE_PHYSICAL);
      out.print(filePath);
      }
     }catch(Exception e){
      out.write(e.toString());
      e.printStackTrace();
     }
     %>

Servlet:实现上传

<form action="servlet/DoUpload" method="post" enctype="multipart/form-data">
--------------------------
public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  SmartUpload su = new SmartUpload();
  su.initialize(this.getServletConfig(), request, response); //初始化
  String allowed = "jpg,bmp,ico,png";
  su.setAllowedFilesList(allowed);
  String unallowed = "bat,jsp,aspx,asp,txt";
  try {
   su.setDeniedFilesList(unallowed);
  } catch (SQLException e) {
   e.printStackTrace();
  }
  su.setMaxFileSize(1024*1024*2);
  try {
   su.upload();
   for(int i =0; i<su.getFiles().getCount(); i++){
    File file = su.getFiles().getFile(i);
    if(file.isMissing())
     continue;
    String desc = su.getRequest().getParameter("desc");
    out.print(desc);
    String fileName = "d:/file/"; //路径必须存在,否则异常
    fileName += file.getFileName();
    out.print(fileName);
    file.saveAs(fileName,SmartUpload.SAVE_PHYSICAL);
   }
  } catch (SmartUploadException e) {
   out.print(e.toString());
   e.printStackTrace();
  }
  out.flush();
  out.close();
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值