OKdevTV Docs
Home OKdevTV
ESC
java 2 min read 3.0 KB Raw Markdown
On this page (2)

Java File Upload

  • multipart/form-data
  • from html
text
<!DOCTYPE html>
<html>
  <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>
  • to java servlet
java
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

  private final static Logger LOGGER =
  Logger.getLogger(FileUploadServlet.class.getCanonicalName());

  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;
  }
}

Issue

  • same file name overwrite issue
    • change name and store original name to somewhere
    • add postfix such as count number, timestamp

ref