javax.servlet.http.Part到java.io.File

我需要帮助代码,用于将javax.servlet.http.Part转换为java.io.File

我发现这个有用的代码,但我需要帮助正确实现代码。

private void processFilePart(Part part, String filename) throws IOException { filename = filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); String prefix = filename; String suffix = ""; if (filename.contains(".")) { prefix = filename.substring(0, filename.lastIndexOf('.')); suffix = filename.substring(filename.lastIndexOf('.')); } File file = File.createTempFile(prefix + "_", suffix, new File(location)); if (multipartConfigured) { part.write(file.getName()); } else { InputStream input = null; OutputStream output = null; try { input = new BufferedInputStream(part.getInputStream(), DEFAULT_BUFFER_SIZE); output = new BufferedOutputStream(new FileOutputStream(file), DEFAULT_BUFFER_SIZE); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; for (int length = 0; ((length = input.read(buffer)) > 0);) { output.write(buffer, 0, length); } } finally { if (output != null) try { output.close(); } catch (IOException logOrIgnore) { } if (input != null) try { input.close(); } catch (IOException logOrIgnore) { } } } put(part.getName(), file); part.delete(); } 

我试图编辑代码以便创建java.io.File作为结果,但我总是有问题。

 private void processFilePart(Part part, String filename) throws IOException { int DEFAULT_BUFFER_SIZE = 2048; filename = filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); String prefix = filename; String suffix = ""; if (filename.contains(".")) { prefix = filename.substring(0, filename.lastIndexOf('.')); suffix = filename.substring(filename.lastIndexOf('.')); } File file = new File(filename); InputStream input = null; OutputStream output = null; try { input = new BufferedInputStream(part.getInputStream(), DEFAULT_BUFFER_SIZE); output = new BufferedOutputStream(new FileOutputStream(file), DEFAULT_BUFFER_SIZE); byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; for (int length = 0; ((length = input.read(buffer)) > 0);) { output.write(buffer, 0, length); } } finally { if (output != null) try { output.close(); } catch (IOException logOrIgnore) { } if (input != null) try { input.close(); } catch (IOException logOrIgnore) { } } // how to get the result part.delete(); } 

转换对象的正确方法是什么?

fileupload示例应用程序 – 取自http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html

fileupload示例说明了如何实现和使用文件上载function。

fileupload示例应用程序由一个servlet和一个HTML表单组成,该表单向servlet发出文件上载请求。

此示例包含一个非常简单的HTML表单,其中包含两个字段:文件和目标。 输入类型文件使用户能够浏览本地文件系统以选择文件。 选择文件后,它将作为POST请求的一部分发送到服务器。 在此过程中,对带有输入类型文件的表单应用了两个强制性限制:

必须将enctype属性设置为multipart / form-data的值。

它的方法必须是POST。

以这种方式指定表单时,整个请求将以编码forms发送到服务器。 然后,servlet处理请求以处理传入的文件数据并从流中提取文件。 目标是文件将保存在计算机上的位置的路径。 按下表单底部的“上载”按钮会将数据发布到servlet,从而将文件保存在指定的目标中。

tut-install / examples / web / fileupload / web / index.html中的HTML表单如下:

    File Upload    
File:
Destination:

当客户端需要将数据作为请求的一部分发送到服务器时,例如上载文件或提交完成的表单时,将使用POST请求方法。 相反,GET请求方法仅向服务器发送URL和标头,而POST请求还包括消息体。 这允许将任意类型的任意长度数据发送到服务器。 POST请求中的标头字段通常表示邮件正文的Internet媒体类型。

在提交表单时,浏览器将内容组合在一起,将所有部分组合在一起,每个部分代表一个表单的字段。 部件以输入元素命名,并使用名为boundary的字符串分隔符彼此分隔。

在选择sample.txt作为将上载到本地文件系统上的tmp目录的文件之后,这就是从fileupload表单提交的数据:

 POST /fileupload/upload HTTP/1.1 Host: localhost:8080 Content-Type: multipart/form-data; boundary=---------------------------263081694432439 Content-Length: 441 -----------------------------263081694432439 Content-Disposition: form-data; name="file"; filename="sample.txt" Content-Type: text/plain Data from sample file -----------------------------263081694432439 Content-Disposition: form-data; name="destination" /tmp -----------------------------263081694432439 Content-Disposition: form-data; name="upload" Upload -----------------------------263081694432439-- 

servlet FileUploadServlet.java可以在tut-install / examples / web / fileupload / src / java / fileupload /目录中找到。 servlet开头如下:

 @WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"}) @MultipartConfig public 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并将文件复制到指定的目标。 该方法的error handling部分捕获并处理了无法找到文件的一些最常见原因。 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("
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; }