public void fileUpload(HttpServletRequest request){ String uploadPath = "fileUpload"; String tmpPath = "tmpUpload"; if (!new File(uploadPath).exists()) { new File(uploadPath).mkdirs(); } if (!new File(tmpPath).exists()) { new File(tmpPath).mkdirs(); } DiskFileUpload fu = new DiskFileUpload(); fu.setSizeMax(4194304); // 设置最大文件尺寸 fu.setSizeThreshold(4096); // 设置缓冲区大小 fu.setRepositoryPath(tmpPath); // 设置临时目录 Iterator it = fu.parseRequest(request).iterator(); while (it.hasNext()) { FileItem fileItem = (FileItem) it.next(); if (!fileItem.isFormField()) { // 非表单域对象 if (fileItem.getSize() > 0) { String ext = fileItem.getName().substring(fileItem.getName().lastIndexOf(".")); String filePath = uploadPath + File.separator + Calendar.getInstance() .getTimeInMillis() + ext; File file = new File(filePath); if (!file.exists()) { file.createNewFile(); } fileItem.write(file); } } } }
jsp文件如下:
<form action="upload.jsp" enctype="multipart/form-data"> <input type="file" name="file"> <input type="file" name="file"> ...... <input type="submit" name="submit" value="upload"> </form>
注: 用到的包 commons-fileupload.jar