文件上传示例应用程序-
来自http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html
fileupload示例说明了如何实现和使用文件上传功能。
fileupload示例应用程序由单个Servlet和HTML表单组成,该HTML表单向Servlet发出文件上传请求。
此示例包括一个非常简单的HTML表单,其中包含两个字段:文件和目标。输入类型file使用户能够浏览本地文件系统以选择文件。选择文件后,它将作为POST请求的一部分发送到服务器。在此过程中,将两个强制性限制应用于具有输入类型文件的表单:
enctype属性必须设置为multipart / form-data的值。
它的方法必须是POST。
当以此方式指定表单时,整个请求将以编码形式发送到服务器。然后,该Servlet处理请求以处理传入的文件数据并从流中提取文件。目的地是文件将保存在计算机上的位置的路径。按下表单底部的“上载”按钮,会将数据发布到servlet,该servlet将文件保存在指定的目标位置。
tut-install / examples / web / fileupload / web / index.html中的HTML格式如下:
<!DOCTYPE html><html lang="en"> <head> <title>File Upload</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <form method="POST" action="upload" enctype="multipart/form-data" > File: <input type="file" name="file" id="file" /> <br/> Destination: <input type="text" value="/tmp" name="destination"/> </br> <input type="submit" value="Upload" name="upload" id="upload" /> </form> </body></html>
当客户端需要将数据发送到服务器作为请求的一部分时,例如上载文件或提交完整的表单时,将使用POST请求方法。相反,GET请求方法仅将URL和标头发送到服务器,而POST请求还包括消息正文。这允许将任何类型的任意长度的数据发送到服务器。POST请求中的标头字段通常指示消息正文的Internet媒体类型。
提交表单时,浏览器将所有部分组合在一起,流式传输内容,每个部分代表表单的一个字段。零件以输入元素命名,并用称为边界的字符串定界符彼此分隔。
在选择sample.txt作为要上传到本地文件系统上tmp目录的文件之后,这是从fileupload表单提交的数据的样子:
POST /fileupload/upload HTTP/1.1Host: localhost:8080Content-Type: multipart/form-data; boundary=---------------------------263081694432439Content-Length: 441-----------------------------263081694432439Content-Disposition: form-data; name="file"; filename="sample.txt"Content-Type: text/plainData from sample file-----------------------------263081694432439Content-Disposition: form-data; name="destination"/tmp-----------------------------263081694432439Content-Disposition: form-data; name="upload"Upload-----------------------------263081694432439--
可以在tut-install / examples / web / fileupload / src / java / fileupload
/目录中找到Servlet FileUploadServlet.java。servlet开始如下:
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})@MultipartConfigpublic class FileUploadServlet extends HttpServlet { private final static Logger LOGGER = Logger.getLogger(FileUploadServlet.class.getCanonicalName());@WebServlet批注使用urlPatterns属性定义servlet映射。
@MultipartConfig批注指示servlet希望使用multipart / form-data MIME类型进行请求。
processRequest方法从请求中检索目标和文件部分,然后调用getFileName方法从文件部分中检索文件名。然后,该方法创建FileOutputStream并将文件复制到指定的目的地。该方法的错误处理部分捕获并处理了无法找到文件的一些最常见原因。processRequest和getFileName方法如下所示:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); // Create path components to save the file final String path = request.getParameter("destination"); final Part filePart = request.getPart("file"); final String fileName = getFileName(filePart); OutputStream out = null; InputStream filecontent = null; final PrintWriter writer = response.getWriter(); try { out = new FileOutputStream(new File(path + File.separator + fileName)); filecontent = filePart.getInputStream(); int read = 0; final byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { out.write(bytes, 0, read); } writer.println("New file " + fileName + " created at " + path); LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", new Object[]{fileName, path}); } catch (FileNotFoundException fne) { writer.println("You either did not specify a file to upload or are " + "trying to upload a file to a protected or nonexistent " + "location."); writer.println("<br/> ERROR: " + fne.getMessage()); LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", new Object[]{fne.getMessage()}); } finally { if (out != null) { out.close(); } if (filecontent != null) { filecontent.close(); } if (writer != null) { writer.close(); } }}private String getFileName(final Part part) { final String partHeader = part.getHeader("content-disposition"); LOGGER.log(Level.INFO, "Part Header = {0}", partHeader); for (String content : part.getHeader("content-disposition").split(";")) { if (content.trim().startsWith("filename")) { return content.substring( content.indexOf('=') + 1).trim().replace(""", ""); } } return null;}


