我正在遵循commons文件上载网站中提供的有关流API的示例。我一直在努力弄清楚如何获取上载文件的文件扩展名,如何将文件写入目录,最糟糕的部分是编写示例注释的人所在的位置,// Process the input stream...这让我想知道这是否太琐碎了,以至于我是唯一一个不知道如何做的人。
// Process the input stream...
在您的HTML文件中使用它:
<form action="UploadController" enctype="multipart/form-data" method="post"> <input type="file"> </form>
并在UploadControllerservlet中的doPost方法内部:
UploadController
doPost
boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String fileName = item.getName(); String root = getServletContext().getRealPath("/"); File path = new File(root + "/uploads"); if (!path.exists()) { boolean status = path.mkdirs(); } File uploadedFile = new File(path + "/" + fileName); System.out.println(uploadedFile.getAbsolutePath()); item.write(uploadedFile); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }