【问题标题】:adding text input to multipart/form-data makes it fail [duplicate]将文本输入添加到 multipart/form-data 使其失败 [重复]
【发布时间】:2025-11-20 14:50:02
【问题描述】:

所以我想做的只是一个传输文本和图像的简单表单。目前,我不能同时做这两个!

这是一个简单的表单代码:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<center>
<h1>File Upload</h1>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<input type="text" name="CaptionBox" />
<input type="file" name="photo" />
<input type="submit" />
</form>
</center>
</body>
</html>

这段代码给了我这个错误:

java.io.IOException: java.io.FileNotFoundException: C:\Users\poste hp\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\maroc_events\uploadFiles (Access denied) 

但是,如果将文本输入收起来,只让文件输入,它就可以了!我不知道为什么!

这里是servlet代码:

@WebServlet("/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet{

/**
 * Name of the directory where uploaded files will be saved, relative to
 * the web application directory.
 */
private static final String SAVE_DIR = "uploadFiles";

/**
 * handles file upload
 */
protected void doPost(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    EventUtil.addImage(request);
    request.setAttribute("message", "Upload has been done successfully!");
    getServletContext().getRequestDispatcher("/message.jsp").forward(
            request, response);
}

}

最后是 Eventutil 类:

package com.utils;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

public class EventUtil {

private static final String SAVE_DIR = "uploadFiles";

public static void addImage(HttpServletRequest request) throws IOException, ServletException{
    String appPath = request.getServletContext().getRealPath("");
    // constructs path of the directory to save uploaded file
    String savePath = appPath + File.separator + SAVE_DIR;
    System.out.println(savePath);

    // creates the save directory if it does not exists
    File fileSaveDir = new File(savePath);
    if (!fileSaveDir.exists()) {
        fileSaveDir.mkdir();
    }

    for (Part part : request.getParts()) {
        String fileName = extractFileName(part);
        part.write(savePath + File.separator + fileName);
    }
}

private static String extractFileName(Part part) {
    String contentDisp = part.getHeader("content-disposition");
    String[] items = contentDisp.split(";");
    for (String s : items) {
        if (s.trim().startsWith("filename")) {
            return s.substring(s.indexOf("=") + 2, s.length()-1);
        }
    }
    return "";
} 
}

谢谢!

编辑: 堆栈跟踪:

java.io.FileNotFoundException: C:\Users\poste hp\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\maroc_events\uploadFiles (Accès refusé)
java.io.FileOutputStream.open(Native Method)
java.io.FileOutputStream.<init>(Unknown Source)
java.io.FileOutputStream.<init>(Unknown Source)
org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.write(DiskFileItem.java:394)
com.utils.EventUtil.addImage(EventUtil.java:28)
com.servlets.UploadServlet.doPost(UploadServlet.java:54)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

【问题讨论】:

  • 如果您包含堆栈跟踪,我们总是更容易提供帮助,但是您是否检查过C:\Users\poste hp\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\maroc_events\uploadFiles 是否存在?如果不是,是来自mkdir() 的错误(参见stacktrace),父目录(maroc_events)是否存在?
  • 是的,它存在,正如我所说,当没有文本输入 @Andreas 时,图像会成功上传
  • 另外,您应该使用新的Path 而不是旧的File。一个原因是它提供了更好的错误消息。

标签: java forms jsp jakarta-ee


【解决方案1】:

write() 方法会抛出错误,因为...\maro‌​c_events\uploadFiles 是一个目录,您无法写入目录。

可以写入该目录中的文件,但这需要文件名。 fileName 很可能是空白的。

不确定,但我相信getParts() 也会返回非文件部分,这意味着它也会返回CaptionBox 字段的部分。尝试打印part.getName() 进行检查。

由于您只需要一个文件,因此请使用 request.getPart("photo") 而不是循环。

【讨论】: