无法发送多部分/表单数据

时间:2019-12-18 16:52:46

标签: java tomcat post servlets jetty

我制作了一个包含两个部分的应用程序:图片和一些文本。代码的开头是:

  @WebServlet("/App")
@MultipartConfig(fileSizeThreshold=1024*1024*10,    // 10 MB
        maxFileSize=1024*1024*50,       // 50 MB
        maxRequestSize=1024*1024*100)       // 100 MB
public class App extends HttpServlet {

    private static final long serialVersionUID = 205242440643911308L;
    private static final String PREFIX = "stream2file";
    private static final String SUFFIX = ".tmp";

    private static final String UPLOAD_DIR = "uploads";

    protected void doPost(HttpServletRequest req,
                          HttpServletResponse resp) throws ServletException, IOException {

        JsonObject servletResponse = new JsonObject();

        System.out.println("------------------------------");
        System.out.println(req.getContentType());
        System.out.println("------------------------------");
        String text = null;
        String uuid = UUID.randomUUID().toString();
        Properties props = new Properties();
        File dbPropsFile = new File("/config.properties");
        FileReader fileReader = new FileReader(dbPropsFile);
        props.load(fileReader);

        for (Part part : req.getParts()) {
            if(getFileType(part).equals("image")) {

代码在

上失败
for (Part part : req.getParts()) {

如果我使用mvn jetty:run运行它,则完全可以正常工作,但是当部署到服务器时,它只会崩溃。请帮忙!!!

在尝试执行System.out.println(req.getContentType());时,在Tomcat和Jetty服务器上为null,但在mvn jetty:run上带有期望值

1 个答案:

答案 0 :(得分:0)

如果HttpServletRequest.getContentType()为空,则您的请求不满足@MultipartConfig的要求,该要求要求Content-Type的值为multipart/form-data

确保首先在网络上正确提交表单。

也许add some unit tests to your project可以确保Servlet的行为符合预期,从而使您可以将注意力集中在表单提交/请求侧。