Как получить параметры multipart / form-data с использованием деталей - PullRequest
0 голосов
/ 19 декабря 2018

Я пытаюсь получить значения из многочастной формы, используя Parts, без использования DiskFileItemFactory.В этом коде я могу обработать файл, но не уверен, как получить другие переданные нефайловые значения.

/**
 * Directory where uploaded files will be saved, its relative to
 * the web application directory.
 */
private static final String UPLOAD_DIR = "uploads";

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // gets absolute path of the web application
    String applicationPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;

    // creates the save directory if it does not exists
    File fileSaveDir = new File(uploadFilePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdirs();
    }
    System.out.println("Upload File Directory="+fileSaveDir.getAbsolutePath());

    String fileName = null;
    //Get all the parts from request and write it to the file on server
    for (Part part : request.getParts()) {
        fileName = getFileName(part);
        part.write(uploadFilePath + File.separator + fileName);
    }

    request.setAttribute("message", fileName + " File uploaded successfully!");
    getServletContext().getRequestDispatcher("/response.jsp").forward(
            request, response);
}

/**
 * Utility method to get file name from HTTP header content-disposition
 */
private String getFileName(Part part) {
    String contentDisp = part.getHeader("content-disposition");
    System.out.println("content-disposition header= "+contentDisp);
    String[] tokens = contentDisp.split(";");
    for (String token : tokens) {
        if (token.trim().startsWith("filename")) {
            return token.substring(token.indexOf("=") + 2, token.length()-1);
        }
    }
    return "";
}

}

1 Ответ

0 голосов
/ 19 декабря 2018

Пожалуйста, найдите ниже:

    @WebServlet(name = "ImageHandler", urlPatterns = {"/ImageHandler"})
@MultipartConfig(maxFileSize = 100 * 1024 * 1024)  // 100MB max
public class ImageHandler extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String name = request.getParameter("name");
        out.println("<br>name: " + name);

        // Create a new file upload handler
        InputStream inputStream = null;

        // obtains the upload file part in this multipart request
        Part filePart = request.getPart("file");

        if (filePart != null) {
            // prints out some information for debugging
            out.println("<br>getName: " + filePart.getName());
            out.println("<br>getSize: " + filePart.getSize());
            out.println("<br>getContentType: " + filePart.getContentType());

            // obtains input stream of the upload file
            //inputStream = filePart.getInputStream();
        }
    }

}

Форма HTML:

<form action="ImageHandler" method="post" enctype="multipart/form-data" role="form">
            Name: <input  maxlength="100" type="text" name="name" class="form-control" placeholder=""  />

            <br>
                file: <input type="file" id="files"  name="file" /> 
            <br>

            <input type="submit" value="submit">
        </form>
...