gpt4 book ai didi

java - GetParts() 在 servlet 中返回 null

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:20 24 4
gpt4 key购买 nike

大家好,我的代码遇到问题,我有一个 jsp 表单,它将文件发送到 servlet 中,当我尝试使用 request.getParts() 提取文件时,当我尝试将其打印到控制台时,它返回 null 值,任何人都可以帮助我。这是我的代码。

我的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>

我的servlet:

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

}

最佳答案

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

关于java - GetParts() 在 servlet 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55137235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com