1

我们有一个在 Undertow 和 SpringBoot 上运行的项目,并且正在尝试添加文件上传。第一次尝试成功,文件已通过使用 绑定到适当的 Bean,StandardServletMultipartResolver并使用application.properties. 然而,我们在错误处理方面遇到了可怕的困难。我们通过将标准解析器配置为 100MB 并使用CommonsMultipartResolver. 然后我们添加了一个像这样的过滤器

@Bean
public Filter filter() {
    return new OncePerRequestFilter() {
        @Override
        protected void doFilterInternal(HttpServletRequest request,
                HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
            try {
                filterChain.doFilter(request, response);
            } catch (ServletException e) {
                if (e.getCause()
                        .getClass()
                        .equals(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException.class)) {
                    int requestSize = request.getContentLength();
                    Collection<Part> parts = request.getParts();
                    List<String> oversizedFields = new LinkedList<>();
                    long uploadSize = 0;
                    for (Part part : new ArrayList<>(parts)) {
                        if (uploadSize + part.getSize() > MAX_UPLOAD_SIZE) {
                            requestSize -= part.getSize();
                            oversizedFields.add(part.getName());
                            request.getParameterMap()
                                    .remove(part.getName());
                            parts.remove(part);
                        } else {
                            uploadSize += part.getSize();
                        }
                    }
                    request.setAttribute("oversizedFields", oversizedFields);
                    SizeModifyingServletRequestWrapper requestWrapper = new SizeModifyingServletRequestWrapper(
                            request, requestSize, uploadSize);
                    filterChain.doFilter(requestWrapper, response);
                }
            }
        }
    };
}

请求包装器:

private static class SizeModifyingServletRequestWrapper extends
        HttpServletRequestWrapper {
    private int size;
    private long sizeLong;

    public SizeModifyingServletRequestWrapper(HttpServletRequest request,
            int size, long sizeLong) {
        super(request);
        this.size = size;
        this.sizeLong = sizeLong;
    }

    @Override
    public int getContentLength() {
        return size;
    }

    @Override
    public long getContentLengthLong() {
        return sizeLong;
    }

    @Override
    public String getHeader(String name) {
        if (FileUploadBase.CONTENT_LENGTH.equals(name)) {
            return Integer.toString(size);
        } else {
            return super.getHeader(name);
        }
    }
}

-@Controller方法然后检查过大的文件并将结果添加到BindingResult,这很好,除了文件没有绑定到 bean 的事实。事实证明CommonsMultipartResolver,当尝试解析请求时,会抛出一个MalformedStreamExceptionin ItemInputStream.makeAvailable(),它总是返回 Message String ended unexpectedly

所以我们重新使用StandardServletMultipartResolver,并且能够RuntimeException很好地捕捉它抛出的问题,但是即使一个文件超出其大小边界,它也绝对不会提供任何表单数据。

我们绝对被难住了,因为不管解析器是否懒惰地工作。如果有人对如何解决此问题有任何进一步的想法,欢迎提出答案=)

更多参考代码:

提取自WebAppInitializer

@Bean(name = "multipartResolver")
public MultipartResolver multipartResolver() {
    StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
    multipartResolver.setResolveLazily(true);
    return multipartResolver;
}

@Bean
public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    factory.setMaxFileSize("2MB");
    factory.setMaxRequestSize("100MB");
    return factory.createMultipartConfig();
}

从控制器中提取:

@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT })
public String saveOrganizationDetails(
        @PathVariable(PATH_VARIABLE_ORGANIZATION_ID) String organizationId,
        @ModelAttribute @Valid Organization organization,
        BindingResult bindingResult, Model model,
        RedirectAttributes redirectAttributes, WebRequest request) {
checkForOversizedFiles(request, bindingResult);
    Map<String, MultipartFile> files = organization.getStyle().whichFiles();
}

private boolean checkForOversizedFiles(WebRequest request,
        BindingResult bindingResult) {
    if (request.getAttribute("oversizedFields", WebRequest.SCOPE_REQUEST) instanceof LinkedList) {
        @SuppressWarnings("unchecked")
        LinkedList<String> oversizedFiles = (LinkedList<String>) request
                .getAttribute("oversizedFields", WebRequest.SCOPE_REQUEST);
        for (String s : oversizedFiles) {
            String errorCode = KEY_ORGANIZATION_LOGO_OVERSIZED_FILE + s;
            bindingResult.rejectValue(s,
                    errorCode);
        }
        return true;
    } else {
        return false;
    }
}

private void handleUpload(Map<String, MultipartFile> files,
        OrganizationStyle style, BindingResult result) {
    for (String filename : files.keySet()) {
        if (processUpload(files.get(filename), filename)) {
            style.setLogoFlag(filename);
        } else {
            result.reject(KEY_ORGANIZATION_LOGO_UPLOAD_FAILURE);
        }
    }
}

processUpload()到目前为止还没有任何功能,这就是为什么我没有在这里包括它。

从 Form-Backing Bean 中提取:

public class OrganizationStyle {
@Transient
private MultipartFile logoPdf;
@Transient
private MultipartFile logoCustomerArea;
@Transient
private MultipartFile logoAssistant;
@Transient
private MultipartFile logoIdentityArea;

<omitting Getters and setters>

private Map<String, MultipartFile> getAllFiles() {
    Map<String, MultipartFile> files = new HashMap<>();
    files.put("logoPdf", logoPdf);
    files.put("logoCustomerArea", logoCustomerArea);
    files.put("logoAssistant", logoAssistant);
    files.put("logoIdentityArea", logoIdentityArea);
    return files;
}

public Map<String, MultipartFile> whichFiles() {
    Map<String, MultipartFile> whichFiles = new HashMap<>();
    for (String name : getAllFiles().keySet()) {
        MultipartFile file = getAllFiles().get(name);
        if (file != null && !file.isEmpty()) {
            whichFiles.put(name, file);
        }
    }
    return whichFiles;
}
}

如前所述,这不是整个代码,而是这个特定问题的必要代码。上传超大文件时抛出的异常是:

(java.io.IOException) java.io.IOException: UT000054: The maximum size 2097152 for an individual file in a multipart request was exceeded

或提到的FileUploadBase.FileSizeLimitExceedeException

最后但并非最不重要的一点是表单页面的摘录

<div id="layoutOne" class="panel-collapse collapse">
    <div class="panel-body">
        <div class="form-group">
            <label for="logoPdf" class="control-label" th:text="#{organizationcontext.groups.addmodal.logo.form.label}">LOGO-FORM</label>
            <input type="file" th:field="*{style.logoPdf}" accept="image/*" />
        </div>
        <div class="form-group">
            <label for="logoCustomerArea" class="control-label" th:text="#{organizationcontext.groups.addmodal.logo.customer.label}">LOGO-ORGANIZATION</label>
            <input type="file" th:field="*{style.logoCustomerArea}" accept="image/*" />
        </div>
        <div class="form-group">
            <label for="logoAssistant" class="control-label" th:text="#{organizationcontext.groups.addmodal.logo.assistant.label}">LOGO-ASSISTANT</label>
            <input type="file" th:field="*{style.logoAssistant}" accept="image/*" />
        </div>
        <div class="form-group">
            <label for="logoIdentityArea" class="control-label" th:text="#{organizationcontext.groups.addmodal.logo.id.label}">LOGO-ID</label>
            <input type="file" th:field="*{style.logoIdentityArea}" accept="image/*" />
        </div>
        <div class="form-group" th:classappend="${#fields.hasErrors('style.cssUrl')}? has-error">
            <label for="style.cssUrl" class="control-label" th:text="#{organizationcontext.groups.addmodal.css.external.label}">CSS-EXTERNAL</label>
            <input th:field="*{style.cssUrl}" class="form-control" type="text" th:placeholder="#{placeholder.css.external}" />
        </div>
        <div class="form-group" th:classappend="${#fields.hasErrors('style.cssCode')}? has-error">
            <label for="style.cssCode" class="control-label" th:text="#{organizationcontext.groups.addmodal.css.input.label}">CSS</label>
            <textarea th:field="*{style.cssCode}" class="form-control" th:placeholder="#{placeholder.css.input}"></textarea>
        </div>
    </div>
</div>

如果您在此处跟踪问题,您应该已经意识到我们已经尝试了几种可能的解决方案,大多数来自这里。现在,过滤器捕获RuntimeException并检查IOException原因,而且大小不再设置在application.properties

任何帮助或建议都将非常感激。

更多信息

因此,我调试StandardServletMultipartResolver并发现它使用 ISO-8859-1-charset 进行解析。这确实产生了预期的效果,即使页面是 UTF-8 编码的并且请求对象也具有 UTF-8-Charset。我一直在尝试使用这样的过滤器强制 ISO-Charset

@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public Filter characterEncodingFilter() {
    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
    characterEncodingFilter.setEncoding("ISO-8859-1");
    characterEncodingFilter.setForceEncoding(true);
    return characterEncodingFilter;
}

但是,由于某种原因,CommonsMultipartResolver找到了一个 UTF-8 编码的请求对象,所以要么这个编码不起作用,要么我犯了另一个我没有看到的错误。

我还试图找到抛出异常的确切时刻,以自己扩展类并确保保留已解析的表单数据,但到目前为止无济于事。

更多信息

正如此处另一个线程所建议的那样,我尝试在请求中强制使用 ISO-8859-1 字符集。起初,这完全绕过CommonsMultipartResolver并弄乱了我的文本,现在它过滤到正确的解析器,但这仍然表明多部分数据中没有文件。仅供参考,我使用的过滤器类:

private class MyMultiPartFilter extends MultipartFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
            HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        request.setCharacterEncoding("ISO-8859-1");
        request.getParameterNames();
        super.doFilterInternal(request, response, filterChain);
    }
}

从中制作了一个 Bean,并将 multipartResolver()-Bean 的名称更改为 filterMultipartResolver()

4

1 回答 1

1

问题的解决方案大致是在我寻找它的时候找到的。它已张贴在这里

由于 WildFly 和 Undertow 在StandardServletMultipartResolver处理CommonsMultipartResolver. 但是,必须在处理其余 POST 数据之前调用它。
为了确保这一点,有必要像这样调用 aMultipartFilter并创建一个filterMultipartResolver-Bean:

@Bean
public CommonsMultipartResolver filterMultipartResolver() {
    return new CommonsMultipartResolver();
}

@Bean
@Order(0)
public MultipartFilter multipartFilter() {
    return new MultipartFilter();
}

这确保首先调用过滤器,然后调用解析器。唯一的缺点是没有开箱即用的方法来限制上传的单个文件大小。这可以通过设置来完成maxUploadSize(value),这限制了整体请求的大小。

最终编辑

所以,这就是我最终使用的,它允许有效上传和处理超大文件。我不确定这在上传大文件时是否同样有效,因为这会在将请求转换为之后FileItems但在解析之前处理过大的文件说FileItems.

我扩展了这样的CommonsMultipartResolver覆盖parseRequest

@Override
protected MultipartParsingResult parseRequest(HttpServletRequest request) {

    String encoding = determineEncoding(request);
    FileUpload fileUpload = prepareFileUpload(encoding);

    List<FileItem> fileItems;
    List<String> oversizedFields = new LinkedList<>();

    try {
        fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
    } catch (FileUploadBase.SizeLimitExceededException ex) {
        fileItems = Collections.emptyList();
        request.setAttribute(ATTR_REQUEST_SIZE_EXCEEDED,
                KEY_REQUEST_SIZE_EXCEEDED);
    } catch (FileUploadException ex) {
        throw new MultipartException(MULTIPART_UPLOAD_ERROR, ex);
    }
    if (maxFileSize > -1) {
        for (FileItem fileItem : fileItems) {
            if (fileItem.getSize() > maxFileSize) {
                oversizedFields.add(fileItem.getFieldName());
                fileItem.delete();
            }
        }
    }
    if (!oversizedFields.isEmpty()) {
        request.setAttribute(ATTR_FIELDS_OVERSIZED, oversizedFields);
    }
    return parseFileItems((List<FileItem>) fileItems, encoding);
}

并添加了通过 bean 配置设置 maxFileSize 的方法。如果超过请求大小,所有值都将被删除,所以要小心,特别是如果你使用_csrf-token或类似的。

在控制器中,现在可以很容易地检查添加的属性并将错误消息放在页面上。

于 2015-05-21T14:30:40.520 回答