0

I am doing project Online Image Gallery, in which I have to upload images. I am doing it with jsp/servlet and IDE is Eclipse. My Jsp file is as follows

<form action="ActionPage" >
    <input type="file" name="myFile">

    <br>
    <input type="submit">
</form>

Here Actionpage is servlet. On Clicking submit button i want the selected file to be stored inside the folder called "IMAGE" inside the WebContent on server and path on database table. If any one know the simple solution please share it.

Thanks in advance.

user1796108
  • 11
  • 1
  • 2

2 Answers2

0

You can read how this is done here

How to upload files to server using JSP/Servlet?

PS: Storing uploaded files inside the applications directory is BAD BAD BAD idea. Think about what would happen if you have your application running for some time, and you want to do a redeploy becase a file is missing some html tag. The upload's directory will be removed by your container! Try using a folder outside of the application's directory, or use a database.

Community
  • 1
  • 1
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
0

This is the easiest solution if You are using jsp to develop your website First of all for taking input from user make a html or jsp page and include tis code in your jsp/html page

First of all download

  • commons-fileupload-1.2.2.jar

  • org.apache.commons.io.jar

and add this jar to your library by right-clicking your project then select build path and then add jar files

    `<form role="form" action="Upload.jsp" method="post"enctype="multipart/form-data">
    <div class="btn btn-success btn-file">
    <i class="fa fa-cloud-upload"></i>
             Browse
    <input type="file" name="file" />
    </div>
    <button type="submit" value="submit" name='submit'>submit</button>`
    </form>

enctype="multipart/form-data" it is necessary

Now make one jsp named upload.jsp( you can have the target jsp with which we are going to save our image to server of any name but remember to put that name in in above code

    <%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
    <%@ page import="javax.servlet.http.*" %>
    <%@ page import="org.apache.commons.fileupload.*" %>
    <%@ page import="org.apache.commons.fileupload.disk.*" %>
    <%@ page import="org.apache.commons.fileupload.servlet.*" %>
    <%@ page import="org.apache.commons.io.output.*" %>

    <%
       String userName = (String) session.getAttribute("User");
      File file ;
      int maxFileSize = 5000000 * 1024;
      int maxMemSize = 5000000 * 1024;
      ServletContext context = pageContext.getServletContext();
      String filePath = context.getInitParameter("file-upload");

      // Verify the content type
      String contentType = request.getContentType();
      if ((contentType.indexOf("multipart/form-data") >= 0)) {

         DiskFileItemFactory factory = new DiskFileItemFactory();
         // maximum size that will be stored in memory
         factory.setSizeThreshold(maxMemSize);
         // Location to save data that is larger than maxMemSize.
         factory.setRepository(new File("C:\\Users\\"));

  // Create a new file upload handler
  ServletFileUpload upload = new ServletFileUpload(factory);
  // maximum file size to be uploaded.
  upload.setSizeMax( maxFileSize );
  try{ 
     // Parse the request to get file items.
     List<FileItem> fileItems = upload.parseRequest(request);

     // Process the uploaded file items
     Iterator i = fileItems.iterator();

     while ( i.hasNext () ) 
     {
        FileItem fi = (FileItem)i.next();
        if ( !fi.isFormField () )   
        {
        // Get the uploaded file parameters
        String fieldName = fi.getFieldName();
        String fileName = fi.getName();
        boolean isInMemory = fi.isInMemory();
        long sizeInBytes = fi.getSize();
        // Write the file
        if( fileName.lastIndexOf("\\") >= 0 ){
        file = new File( filePath + 
        fileName.substring( fileName.lastIndexOf("\\"))) ;
        }else{
        file = new File( filePath + 
        fileName.substring(fileName.lastIndexOf("\\")+1)) ;
        }
        fi.write( file ) ;

        request.setAttribute("Success", "Successfully Uploaded");
        RequestDispatcher rd = request.getRequestDispatcher("/UploadFiles.jsp");
        rd.forward(request, response);
        }
     }

  }catch(Exception ex) {
     System.out.println(ex);
  }
      }else{
         request.setAttribute("Error", "Error!!");
        RequestDispatcher rd =request.getRequestDispatcher("/UploadFiles.jsp");
        rd.forward(request, response);
      }
   %>

please don't get confused just copy this code and once you go through this i am sure you will get to know about code

Now the last thin you have to do is to add something to web.xml if you don't have this file then create this...

 <context-param>
    <description>Location to store uploaded file</description>
    <param-name>file-upload</param-name>
    <param-value>
             C:\\Users\\
    </param-value>
</context-param>

just add above code to web.xml you can change the address where your images will be uploaded as desired ( change param-value for this)

In case you face any problem let me know

Aditya Lodha
  • 106
  • 1
  • 12