servlet如何在一个请求中处理多个上传的文件

时间:2017-06-17 12:42:36

标签: java tomcat servlets

我知道如何在servlet中只上传一个文件时保存它。
HTML

<form action="storeArticle" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    ...
</form>

Servlet可以保存上传的文件,如下所示:

Part part = request.getPart("file");
File file = new File(filePath);
try (InputStream inputStream= part.getInputStream()) { // save uploaded file
    Files.copy(inputStream, file.toPath());
}

例如,在https://stackoverflow.com/questions/ask中,用户可以通过单击唯一的图像图标来选择上传多个图像。但是当多次上传多个文件时,servlet如何保存这些上传的文件?
HTML < / p>

<input type="file" name="file[]" multiple >

1 个答案:

答案 0 :(得分:0)

<form action="storeArticle" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="file" name="file2">
<input type="file" name="file3">

</form>

servlet执行此操作

Part part = request.getPart("file");
 File file = new File(filePath);
 try (InputStream inputStream= part.getInputStream()) { // save uploaded file
  Files.copy(inputStream, file.toPath());
 }


  Part part = request.getPart("file2");
  File file = new File(filePath);
 try (InputStream inputStream= part.getInputStream()) { // save uploaded file
  Files.copy(inputStream, file.toPath());
 }



  Part part = request.getPart("file3");
  File file = new File(filePath);
  try (InputStream inputStream= part.getInputStream()) { // save uploaded file
    Files.copy(inputStream, file.toPath());
   }