使用 apache-commons-fileupload 在 Spring 中上传文件时出现问题

Problem while uploading file in Spring with apache-commons-fileupload

我正在尝试使用本地 tomcat 容器在基于 Spring MVC 构建的 Web 应用程序中上传图像,但代码继续抛出 NullPointerException.

我已经在网上搜索教程,但 none 有用,特别是我遵循了 webSystique、Baeldung 和 mkyong 网站提供的教程。 一切顺利,包括验证,直到获取文件。
所以 Spring 配置和 webapp 是正确的,据我所知,除了下面显示的上传部分。

这是 AppConfig.java 中为 apache-commons 配置 MultipartResolver 的代码:

@Bean
public CommonsMultipartResolver getResolver() throws IOException{

    CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    resolver.setMaxUploadSize(5242880); //max file size set to 5MB

    return resolver;
}

这是代表文件的模型Image.java文件:

public class Image {

private MultipartFile profilePicture;

public MultipartFile getProfilePicture() {
    return profilePicture;
}

public void setProfilePicture(MultipartFile profilePicture) {
    this.profilePicture = profilePicture;
}
}

重定向到表单的控制器方法:

@RequestMapping(value = "/upload-{id}", method = RequestMethod.GET)
public String uploadPage(ModelMap model){

    Image image = new Image();
    model.addAttribute("image", image); //set attribute to request map

    return "uploadForm";
}

uploadForm.jps页面中的表单代码:

        <form:form method="POST" modelAttribute="image" enctype="multipart/form-data">
            <div class="row">
                <div class="form-group col-md-12">
                    <div class="col-md-7">
                        <form:input path="profilePicture" type="file" id="profilePicture"></form:input>
                        <form:errors path="profilePicture" cssClass="text-danger"></form:errors>
                    </div>
                </div>
            </div>
            <div class="row">
                <input type="submit" value="upload" class="btn btn-primary btn-sm">
            </div>
        </form:form>

最后,映射到新路径上传文件的方法:

@RequestMapping(value = "/upload-{id}", method = RequestMethod.POST)
public String fileUpload(@Valid Image profilePicture, BindingResult result, @PathVariable int id, ModelMap model) throws IOException {

    if(result.hasErrors()){ //in case of validation error redirect to form page
        return "uploadForm";
    }

    MultipartFile multipartFile = profilePicture.getProfilePicture();

    byte[] source = multipartFile.getBytes(); //source file bytes array
    File dest = new java.io.File(UPLOAD_LOCATION + profilePicture.getProfilePicture().getOriginalFilename()); //destination file
    //copying the file to the new position
    FileCopyUtils.copy(source, dest);

    String fileName = multipartFile.getOriginalFilename(); //original name of file got and saved in attributes map
    employeeService.updateImage(id, fileName);
    model.addAttribute("fileName", fileName);

    return "fileUploaded";
}

UPLOAD_LOCATION 是在控制器 class 中定义的,行是:

private static final String UPLOAD_LOCATION = "C:/EmployeeManager/";

和 O.S。是 windows.

fileUpload方法中抛出异常在后续行:
byte[] source = multipartFile.getBytes(); //source file bytes array

这是日志显示的根本原因:

java.lang.NullPointerException
employeeManager.controller.FileController.fileUpload(FileController.java:80)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

您的问题是由 NullPointerException 引起的,因此您的问题的解决方案非常简单,请确保您没有尝试访问 null 对象的成员。

第80行抛出异常,你自己已经确定:

java.lang.NullPointerException
employeeManager.controller.FileController.fileUpload(FileController.java:80)
byte[] source = multipartFile.getBytes(); //source file bytes array

所以只要确保 multipartFileprofilePicture 对象在被访问之前都不为空。根据您的堆栈跟踪,问题出在这两个变量之一。