GetParts () возвращает ноль в сервлете - PullRequest
1 голос
/ 13 марта 2019

Здравствуйте, ребята, я столкнулся с проблемой с моим кодом, у меня есть форма JSP, которая отправляет файл в сервлет, и когда я пытаюсь извлечь файл с помощью request.getParts (), он возвращает нулевое значение, когда я пытаюсь напечататьэто к консоли, может кто-нибудь помочь мне, пожалуйста.вот мой код.

мой jsp:

 <!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="/PartsServlet" 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>

Мой сервлет:

package Servv;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class PartsServlet
 */
@WebServlet("/PartsServlet")
public class PartsServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public PartsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
        System.out.println("Get Parts "+request.getPart("file"));
        System.out.println("Get Parts "+request.getPart("destination"));
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

1 Ответ

0 голосов
/ 13 марта 2019
Add @MultipartConfig annotation.
Always parse your request body only once and store it in a list.    
so that one part cannot consume it.

 List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList());

    for (Part part : fileParts) { 

    }

File uploads = new File("/path/to/uploads");
File file = File.createTempFile("somefilename-", ".ext", uploads);

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
...