servlet接收文件
时间: 2023-12-09 22:02:19 浏览: 156
要在Servlet中接收文件,需要使用`HttpServletRequest`对象的`getPart`方法获取文件的Part对象,然后使用Part对象的`getInputStream`方法获取文件的输入流,最后将文件保存到目标位置。
以下是一个简单的示例代码,演示了如何在Servlet中接收并保存上传的文件:
```java
@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取上传的文件
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
// 将上传的文件保存到目标位置
InputStream inputStream = filePart.getInputStream();
OutputStream outputStream = new FileOutputStream("/path/to/destination/" + fileName);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
// 返回上传成功的消息
response.getWriter().println("文件上传成功");
}
}
```
在上面的代码中,`@MultipartConfig`注解用于声明Servlet支持文件上传,`request.getPart("file")`用于获取名为"file"的文件Part对象,然后通过Part对象的`getSubmittedFileName`方法获取文件名,最后使用Part对象的`getInputStream`方法获取文件输入流。保存文件时,我们使用了Java IO API,将文件流写入到目标位置。最后,向客户端发送上传成功的消息。
阅读全文
相关推荐

















