天天看点

Web文件上传组建

文件上传需要用到阿帕奇的commons-fileupload.jar组件,本帖带有附件

将commons-fileupload.jar导入WEB-INF/lib下

Servlet类,记住要在XML中作相应的配置。

保存路径为该项目下temp路径

public class Upload extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

      throws IOException, ServletException {

    parseRequest(request);

  }

public HashMap parseRequest(HttpServletRequest request) {

     HashMap<String,String> paramMap = new HashMap<String,String>();

     DiskFileUpload dfu = new DiskFileUpload(); //获取文件上传处理对象.

     dfu.setSizeMax(1024 * 1024 * 100);//设置允许上传文件大小上限.

     dfu.setSizeThreshold(4096);//设置缓冲区大小.

     dfu.setRepositoryPath(this.getServletContext().getRealPath("/temp/buffer"));//设置临时文件夹.

     try {

         List list = dfu.parseRequest(request);//解析request.

         Iterator it = list.iterator();

         while (it.hasNext()) {

             FileItem fi = (FileItem) it.next();

             if (fi.isFormField()) {//如果是普通文本.

                 paramMap.put(fi.getFieldName(), fi.getString());

             } else {//否则是文件.

                 String tmpFileName = "";

                 if (!fi.getName().equals("")) {// 如果有传文件.

                     tmpFileName = FileName.getRndFileName(fi.getName()); 

                   //将文件保存到服务器.

                     fi.write(new File(this.getServletContext().getRealPath("/temp/" + tmpFileName)));

                 }

                 paramMap.put(fi.getFieldName(), tmpFileName);

             } }    

     } catch (Exception e) {     e.printStackTrace();    }

        return paramMap;

     }

}

JSP中的上传构建,将表单提交到之前Servlet的地址

<body>

     <form name="myform" id="myform" action="./servlet/fileupload" method="post" enctype="multipart/form-data">

             File:<br>

             <input type="file" name="myfile"><br>

             <br>

             <input type="submit" name="submit" value="Commit">

        </form>

    </body>

继续阅读