在spring中上传文件时出现NullPointException

时间:2017-08-28 10:12:14

标签: spring jsp spring-mvc spring-boot multipartform-data

我尝试将 .csv 文件的数据上传到数据库中,但是当我上传并提交它时,它会抛出 nullpointexception 。意思是,当我在控制器中打印 name 时,会打印 name ,但是当我尝试获取该文件时,它会显示 null

FileUpload模型类

public class FileUpload {
    private CommonsMultipartFile[] files;   
    private String name;

    // Getters and setters
}

控制器

@RequestMapping(value = "uploadPage", method = RequestMethod.GET)
    public ModelAndView uploadPage() {
        ModelAndView model = new ModelAndView("upload_page");
        FileUpload formUpload = new FileUpload();
        model.addObject("formUpload", formUpload);
        return model;
    }

    @RequestMapping(value = "/doUpload", method = RequestMethod.POST)
    public String doUpload(@ModelAttribute("formUpload") FileUpload fileUpload, BindingResult result) throws IOException, JAXBException {

        System.out.println("myfirl "+fileUpload.getFiles());  // output is null
        System.out.println("name "+fileUpload.getName());  // name is displaying

        //other stuffs

}

upload_page

<spring:url value="/doUpload" var="doUploadURL"/> 
<form:form method="post" modelAttribute="formUpload" action="${doUploadURL }" enctype="multipart/form-data">
     <form:input path="files" type="file" multiple="multiple"/>
     <form:input path="name" type="text"/>    
     <button type="submit">Upload</button>
</form:form>

WebConfig

@Bean(name="multipartResolver")
public CommonsMultipartResolver getResolver(){
    CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver();
    commonsMultipartResolver.setMaxUploadSizePerFile(20*1024*1024);

    return commonsMultipartResolver;
}

我试图在很多方面对其进行排序,但失败了。有人试图解决它吗?提前致谢

1 个答案:

答案 0 :(得分:0)

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody
public String uploadFileHandler(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
         System.out.println(file.getName);
        }
}

或者你可以那样做

   @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public String uploadFileHandler(MultipartHttpServletRequest  request) {
            Iterator<String> itr = request.getFileNames();
            while (itr.hasNext()){
               System.out.println(itr.next().toString());
            }
....
    }