-2

I want to take image as input into my web page. I have written following code in my jsp for this :-

<form action="Upload" method="get" enctype="multipart/form-data">
    Image<input type="file" name="image" accept="image/jpg" id="image">
    <input type="submit" value="submit">
</form>

but I do not know how to receive the "image" parameter in a servlet that is whether it should be a input stream or file, I have no idea. Please tell me the correct code for it.

Gaurav Mahindra
  • 424
  • 2
  • 6
  • 21
  • Possible duplicate of [How to upload files to server using JSP/Servlet?](http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet) – seenukarthi Apr 04 '16 at 17:24

3 Answers3

0

Use Apache Commons File. The form method must be method="POST". Then in your web.xml you need to map the request to your servlet:

<servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>com.stackoverflow.MyServletClass</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/Upload</url-pattern>
</servlet-mapping>

Then you write a class that extends HttpServlet and implement to doPost() method.

well, just go here: http://www.codejava.net/java-ee/servlet/apache-commons-fileupload-example-with-servlet-and-jsp

Jack Flamp
  • 1,223
  • 1
  • 16
  • 32
0

After painstaking efforts and google search I found a solution to my problem. A page from Stackoverflow helped very much. First I changed the get method of my form to post like this

<form action="Upload" method="post" enctype="multipart/form-data">
    Image<input type="file" name="image" id="image" accept="image/jpg">
    <input type="submit" value="submit">
</form>

Then I wrote the following servlet code. We accept the <input type="file">data as Part data in servlet. Then we convert it to input stream. The input stream then can be saved in database. Here is my Servlet:-

package controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import model.ConnectionManager;

@MultipartConfig(location="/tmp", fileSizeThreshold=1048576, maxFileSize=20848820, maxRequestSize=418018841)
public class Upload extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Part filePart=request.getPart("image");`// Retrieves <input type="file" name="image">`
        String filePath = filePart.getSubmittedFileName();//Retrieves complete file name with path and directories 
        Path p = Paths.get(filePath); //creates a Path object
        String fileName = p.getFileName().toString();//Retrieves file name from Path object
        InputStream fileContent = filePart.getInputStream();//converts Part data to input stream

        Connection conn=ConnectionManager.getConnection();
        int  len=(int) filePart.getSize();
        String query = ("insert into IMAGETABLE(ID,NAME,LENGTH,IMAGE) VALUES(?,?,?,?)");


        try {
            PreparedStatement pstmt = conn.prepareStatement(query);
            pstmt.setInt(1, 5);
            pstmt.setString(2, fileName);
            pstmt.setInt(3, len);
            pstmt.setBinaryStream(4, fileContent, len);
            success=pstmt.executeUpdate();
        } catch (SQLException ex) {
            System.out.println("Error : "+ex.getMessage());
        }finally{
            try{
                if(fileContent!=null)fileContent.close();
                if(conn!=null)conn.close();
            }catch(IOException | SQLException ex){
                System.out.println("Error : "+ex.getMessage());
            }
        }

    }

}

After execution, it does the job successfully. We accept the image from user and save it in database. Hope this solution will help all :)

Gaurav Mahindra
  • 424
  • 2
  • 6
  • 21
0

For upload file in folder we need first create html file and Second jsp , In HTML write code like:

<input type="file" name="image" class="form-control" required>

In JSP write code kike:

MultipartRequest m = new MultipartRequest(request, "PathOfFile")

Note: You must add the following jar files

  1. commons.fileupload
  2. cos.jar file
  3. commons.io.jar file
alea
  • 980
  • 1
  • 13
  • 18