Java+Spring: Can i upload file if I have path without HttpRequest?

I`m doing so

protected ModelAndView onSubmit(HttpServletRequest request,
       HttpServletResponse response, Object command, BindException errors)
       throws Exception {
    MultipartFile multipartFile = null;
    File destFile = new File(
            "/home/stas/eclipse/" + request.getParameter("fileName"));
multipartFile.transferTo(destFile);

But i have exception

27.03.2012 20:39:45 org.apache.catalina.core.StandardWrapperValve invoke 
SEVERE: Servlet.service() for servlet [springapp] in context with 
    path [/springapp] threw exception [Request processing failed; 
    nested exception is java.lang.NullPointerException] with root cause
    java.lang.NullPointerException

Upvotes: 0

Views: 1089

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340883

The NullPointerException is quite obvious:

MultipartFile multipartFile = null;
File destFile = new File("/home/stas/eclipse/"+request.getParameter("fileName"));
multipartFile.transferTo(destFile);   <-----Exception

multipartFile variable is never initialized and throws NPE when being first accessed.

You can get all uploaded files from request using:

public ModelAndView onSubmit(HttpServletRequest request, /*...*/) {
  MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
  Map<String, MultipartFile> files = multipartRequest.getFileMap();

Upvotes: 4

Related Questions