panda

IT高薪不是梦!!

统计

留言簿

阅读排行榜

评论排行榜

文件上传(FileUpload)

1.使用JAR
      jsp文件上传主要使用了两个jar包,commons-fileupload-1.2.1.jar和commons-io-1.4.jar
2.代码实现
     public class UploadServlet extends HttpServlet {

 /**
  *
  */
 private static final long serialVersionUID = 1L;

 private ServletContext sc;

 private String savePath;

 @Override
 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  doPost(request, response);
 }

 @Override
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  System.out.println("请求进来了..........");

  // 设置请求的编码
  request.setCharacterEncoding("UTF-8");

  DiskFileItemFactory factory = new DiskFileItemFactory();//创建一个磁盘文件工厂
  ServletFileUpload upload = new ServletFileUpload(factory);

  try {
   List items = upload.parseRequest(request);
   Iterator it = items.iterator();
   while (it.hasNext()) {
    FileItem item = (FileItem) it.next();

    if (item.isFormField()) {
     System.out.println("表单的参数名称:" + item.getFieldName()
       + ",对应的参数值:" + item.getString("UTF-8"));
    } else {
     // 获取文件扩展名
     String strtype = item.getName().substring(
       item.getName().length() - 3,
       item.getName().length());
     strtype = strtype.toLowerCase();

     if (strtype == "jpg" || strtype == "gif"
       || strtype == "txt") {
      if (item.getName() != null
        && !item.getName().equals("")) {
       System.out.println("上传文件的大小:" + item.getSize());
       System.out.println("上传文件的类型:"
         + item.getContentType());
       System.out.println("上传文件的名称:" + item.getName());

       System.out.println("文件的扩展名" + strtype);
       File tempFile = new File(item.getName());
       File file = new File(
         sc.getRealPath("/") + savePath, tempFile
           .getName());
       item.write(file);

       request.setAttribute("upload.message", "上传文件成功!");

      } else {
       request.setAttribute("upload.message",
         "没有选择上传文件获取格式不支持");
      }
     } else {
      request.setAttribute("upload.message", "上传文件格式不支持");
     }
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
   request.setAttribute("upload.message", "上传文件不成功!");
  }
  // 转发
  request.getRequestDispatcher("/uploadResult.jsp").forward(request,
    response);
 }

 @Override
 public void init(ServletConfig config) throws ServletException {

  savePath = config.getInitParameter("savePath");
  sc = config.getServletContext();
 }

posted on 2009-11-08 16:30 IT追求者 阅读(155) 评论(0)  编辑  收藏 所属分类: Jsp


只有注册用户登录后才能发表评论。


网站导航: