处理 HTTPmultipart/form-data
servlet 中的请求,使用Apache Commons 文件上传 http://commons.apache.org/fileupload。您最终应该将上传的文件放在FileItem http://commons.apache.org/fileupload/apidocs/org/apache/commons/fileupload/FileItem.html。它有一个write()
method.
String filename = FilenameUtils.getName(fileItem.getName());
fileItem.write(new File("c:/upload", filename)); // Name must be unique!
有关使用指南和更多代码示例,只需查看他们的用户指南 http://commons.apache.org/fileupload/using.html.
要显示文件夹中的文件列表,您需要使用java.io.File http://download.oracle.com/javase/6/docs/api/java/io/File.htmlAPI,它有一个listFiles()
方法返回某个路径中所有文件(路径)的列表。在预处理中进行servlet https://stackoverflow.com/tags/servlets/info它将请求转发到 JSP 以显示列表。
File[] files = new File("c:/upload").listFiles();
request.setAttribute("files", files);
request.getRequestDispatcher("/WEB-INF/uploads.jsp").forward(request, response);
In the /WEB-INF/uploads.jsp
文件使用JSTL https://stackoverflow.com/tags/jstl/info <c:forEach>
迭代File[]
.
<c:forEach items="${files}" var="file">
<c:out value="${file.name}" /> (${file.length / 1024}KB)<br/>
</c:forEach>
请注意,这当然可以进行更多(UI)微调,但这取决于您。我假设您已经了解 HTML/JSP/Servlet 基础知识。