1

This is my controller class

@Controller  
public class UploadController {  

 @Autowired  
 UploadDAO  uploaddao;

 @RequestMapping("/upload")  
 public ModelAndView getUploadForm(@ModelAttribute("upload") Upload uploadedFile,BindingResult result) {  
  return new ModelAndView("insertfile");  
 }  

 @RequestMapping("/fileUpload")  
 public ModelAndView fileUploaded(  
   @ModelAttribute("uploadedFile") Upload uploadedFile,  
   BindingResult result) {  
  InputStream inputStream = null;  
  OutputStream outputStream = null;  

  MultipartFile file = uploadedFile.getFile();  

  String fileName = file.getOriginalFilename();  

  if (result.hasErrors()) {  
   return new ModelAndView("uploadForm");  
  }  

  try {  
   inputStream = file.getInputStream();  

   File newFile = new File("D:/try" + fileName);  
   if (!newFile.exists()) {  
    newFile.createNewFile();  
   }  
   outputStream = new FileOutputStream(newFile);  
   int read = 0;  
   byte[] bytes = new byte[1024];  

   while ((read = inputStream.read(bytes)) != -1) {  
    outputStream.write(bytes, 0, read);  
   }  
  } catch (IOException e) {  
   // TODO Auto-generated catch block  
   e.printStackTrace();  
  }  

  return new ModelAndView("showFile", "message", fileName);  
 }  

} 

Here is my model class

@Entity
@Table(name="upload_files")
public class Upload
{
    @Id
    @Column
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int File_Id; 
    @Column
    private  int User_Id;
    @Column
    private String Title;
    @Column
    private String Description;
    @Column
    private String Category;
    @Column
    private String Area;
    @Column
    private String Author;
    //@Column
    //private String Path;
    @Column
    private String Grant_Status;
    @Column
    private Date InsertedDate;

    @Column
    private Date InsertedTime;

    @Transient
    private MultipartFile file;  
     public MultipartFile getFile()
     {
         System.out.println("file"+file);  
         return file;  
     }  

     public void setFile(MultipartFile file) {  
      this.file = file;  
     }  


    public int getUser_Id() {
        return User_Id;
    }
    public void setUser_Id(int user_Id) {
        User_Id = user_Id;
    }
    public String getTitle() {
        return Title;
    }
    public void setTitle(String title) {
        Title = title;
    }
    public String getDescription() {
        return Description;
    }
    public void setDescription(String description) {
        Description = description;
    }
    public String getCategory() {
        return Category;
    }
    public void setCategory(String category) {
        Category = category;
    }
    public String getArea() {
        return Area;
    }
    public void setArea(String area) {
        Area = area;
    }
    public String getAuthor() {
        return Author;
    }
    public void setAuthor(String author) {
        Author = author;
    }
    /*public String getPath() {
        return Path;
    }
    public void setPath(String path) {
        Path = path;
    }*/
    public String getGrant_Status() {
        return Grant_Status;
    }
    public void setGrant_Status(String grant_Status) {
        Grant_Status = grant_Status;
    }

    public Date getInsertedDate() {
        return InsertedDate;
    }
    public void setInsertedDate(Date insertedDate) {
        InsertedDate = insertedDate;
    }
    public Date getInsertedTime() {
        return InsertedTime;
    }
    public void setInsertedTime(Date insertedTime) {
        InsertedTime = insertedTime;
    }
} 

here is my dao class

@Repository
public class UploadDAO 
{


    @Autowired
    SessionFactory sessionFactory;

    @Transactional
    public String uploadFile(Upload s)
    {
        try
        {
            Session session=this.sessionFactory.openSession();
            Transaction tr=session.beginTransaction();
            session.save(s);                            //insert
            tr.commit();
            session.close();
            System.out.println("dao");
        }
        catch(Exception e)
        {
            System.out.println(e.getCause());
        }
        return "Record Inserted...";
    }

}

jsp page

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<%@taglib uri="http://java.sun.com/jstl/core_rt"  prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="fileUpload"  method="post" modelAttribute="upload">

    <table>

            <tr>
                <td>User_Id:</td>
                <td><input name="User_Id"/></td>
            </tr>
            <tr>
                <td>Title:</td>
                <td><input name="Title"/></td>
            </tr>
            <tr>
                <td>Description:</td>
                <td><input name="Description"/></td>
            </tr>


            <tr>
                <td>Category:</td>
                <td><input name="Category"/></td>
            </tr>

            <tr>
                <td>Area:</td>
                <td><input name="Area"/></td>
            </tr>

            <tr>
                <td>Author:</td>
                <td><input name="Author"/></td>
            </tr>

        <tr>  
         <td>Upload File: </td>  
         <td><input type="file" name="file" />  
         </td>  
       </tr> 


            <!-- <tr>
                <td></td>
                <td><input type="hidden" name="file" /></td>
            </tr> -->
            <tr>
                <td colspan="2">
                <input type="submit" value="upload">
<!--                 <input type="submit" name="action" value="add"> -->
<!--                <input type="submit" name="action" value="edit"> -->
<!--                <input type="submit" name="action" value="delete"> -->
<!--                <input type="submit" name="action" value="search">  -->
                </td>
            </tr>
        </table>
</form>
</body>
</html>

Error trace:

Dec 22, 2015 4:45:35 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/DataRepository/] in DispatcherServlet with name 'DispatcherServlet'
filenull
filenull
Dec 22, 2015 4:46:04 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [DispatcherServlet] in context with path [/DataRepository] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at org.controller.UploadController.fileUploaded(UploadController.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

it gives null pointer exception after submitting upload button i am using transient for MultiPartFile because i don't want to store file into database i just want to store is path and other details.

Slava Semushin
  • 14,904
  • 7
  • 53
  • 69
jasmin
  • 31
  • 1
  • 8
  • 1
    can you post your error trace? – soorapadman Dec 22 '15 at 10:41
  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Tom Dec 22 '15 at 11:20
  • 1
    Your `file` in `Upload` is `null`. Btw shouldn't `@ModelAttribute("uploadedFile") Upload uploadedFile` be `@ModelAttribute("upload") Upload uploadedFile`? – Tom Dec 22 '15 at 11:22
  • How can i resolve this problem so file can be uploaded – jasmin Dec 22 '15 at 11:26
  • @tom Why you didn't post it as an answer? – Slava Semushin Dec 22 '15 at 11:29
  • 1
    @SlavaSemushin Because this is an assumption and assumptions belong to a comment, not into an answer :P. – Tom Dec 22 '15 at 11:35
  • can you please help me to sole this problem @ tom? – jasmin Dec 22 '15 at 11:43
  • Please change @ModelAttribute("uploadedFile") to @ModelAttribute("upload") in fileUploaded() method. Want to learn more about spring mvc file upload. http://www.expertwebindia.com/spring-mvc-file-upload-example/ – Gaurav Srivastav Dec 22 '15 at 13:17

0 Answers0