处理 multipart/form-data

multipart/form-data Content Type,专门用于处理包含二进制数据(如图片、视频或文档)和常规文本数据的表单,通常用来上传文件。

要处理 multipart/form-data 请求,我们必须用 @MultipartConfig 或在 web.xml 中配置 Servlet。

@MultipartConfig 提供了各种参数来控制文件上传行为,如 location(临时存储目录)、maxFileSize(单个上传文件的最大大小)和 maxRequestSize(整个请求的最大大小):

@MultipartConfig(fileSizeThreshold = 1024 * 1024, 
  maxFileSize = 1024 * 1024 * 5, 
  maxRequestSize = 1024 * 1024 * 5 * 5)
public class FileUploadServlet extends HttpServlet {
    // ...
}

在 Servlet 中,我们可以使用 getPart(String name) 方法获取 multipart/form-data 中特定 Part(部分)的信息,或者使用 getParts() 方法获取所有 Part 的信息。Part 接口提供了访问文件名、内容类型、大小和输入流等详细信息的方法。

使用 POST 请求上传文件示例如下:

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

    String uploadPath = getServletContext().getRealPath("") + 
      File.separator + UPLOAD_DIRECTORY;
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    Part filePart = request.getPart("file");
    if (filePart != null) {
        String fileName = Paths.get(filePart.getSubmittedFileName())
          .getFileName().toString();
        if(fileName.isEmpty()){
            response.getWriter().println("Invalid File Name!");
            return;
        }
        if(!fileName.endsWith(".txt")){
            response.getWriter().println("Only .txt files are allowed!");
            return;
        }

        File file = new File(uploadPath, fileName);

        try (InputStream fileContent = filePart.getInputStream()) {
            Files.copy(fileContent, file.toPath(), 
              StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            response.getWriter().println("Error writing file: " + 
              e.getMessage());
            return;
        }

        response.getWriter()
            .println("File uploaded to: " + file.toPath());
    } else {
        response.getWriter()
            .println("File upload failed!");
    }
}
posted @ 2024-09-04 10:22  秋水秋色  阅读(294)  评论(0)    收藏  举报