Home Answers Viewqa JSP-Servlet form based file upload using servlets

 
 


sridivya pathaneni
form based file upload using servlets
3 Answer(s)      2 years ago
Posted in : JSP-Servlet

Hai all,

I wrote a program to upload a file into specified directory and store the file path and username into database. for that i created a html page having browse option and text box i used commons-fileupload and commons-io APIs.

while i enterd username and upload file path

it uploaded successfully but in database table it gives null value for username and filepath was inserted successfully

is there any enctype="multipart/form-data" issue in case of giving null value for text field username

can any one help me

Thanks&Regards P.SriDivya

View Answers

May 30, 2011 at 12:27 PM


Please visit the following link:

http://www.roseindia.net/servlets/upload-image.shtml


June 2, 2011 at 5:39 PM


Hi Everyone,

I wrote a program to upload an image file into specified directory. In my jsp page i take two input box one as text type and other one is file type as follows.

 <input type="text" name="CategoryName">
 <input type="file" name="txtImgName">

<form action="uploadservlet" enctype="multipart/form-data" method="POST">

<input type="text" name="CategoryName">
<input type="file" name="txtImgName"><br>
<input type="Submit" value="Upload File"><br>

</form>

public class Commonsfileuploadservlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private static final String TMP_DIR_PATH = "c:\\tmp";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "/files";
    private File destinationDir;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        tmpDir = new File(TMP_DIR_PATH);
        tmpDir.getName();
        System.out.println("inside 0124 init function##########    " + tmpDir.getName());
        if (!tmpDir.isDirectory()) {
            System.out.println("inside 1111111111");
            throw new ServletException(TMP_DIR_PATH + " is not a directory");
        } else {
            System.out.println("tmpDir.isDirectory() is directory......");
        }

        System.out.println("after 22222#########");
        String realPath1 = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        System.out.println("realpath 111111111 - > " + realPath1);
        String realPath = "d:\\tmp";

        System.out.println("after 3333######### real path" + realPath);
        destinationDir = new File(realPath);
        System.out.println("after 444#########");
        if (!destinationDir.isDirectory()) {
            System.out.println("insideeeeeeeee");
            throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
        } else {
            System.out.println("not directry again***********");

        }
        System.out.println("after destination#########");

    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String test="";
        test=request.getParameter("temptest");
        System.out.println("test---- > "+test);
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
        /*
         * Set the temporary directory to store the uploaded files of size above threshold.
         */
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
                } else {
                    //Handle Uploaded files.
                    out.println("Field Name = " + item.getFieldName()
                            + ", File Name = " + item.getName()
                            + ", Content type = " + item.getContentType()
                            + ", File Size = " + item.getSize());
                    String catadd = "s" + "16" + ".png";
                    //  File file = new File(destinationDir, item.getName());
                    File file = new File(destinationDir, catadd);
                    item.write(file);
                    System.out.println("File write successfullyYYYYYY...0201.....###################");
                }
                out.close();
            }
        } catch (FileUploadException ex) {
            log("Error encountered while parsing the request", ex);
        } catch (Exception ex) {
            log("Error encountered while uploading file", ex);
        }

    }

in above servlet i m not able to get "CategoryName" value of jsp input box.but when i remove <enctype="multipart/form-data"> like :
<form action="Commonsfileuploadservlet" method="POST">

then i get the "CategoryName" value.can anyone please suggest me what thing i m missing?

thanks Ashwani


June 2, 2011 at 5:54 PM


Hi evryone,

I wrote a program to upload an image file into specified directory. In my jsp page i take two input box one as text type and other one is file type as follows.

 <input type="text" name="CategoryName">
 <input type="file" name="txtImgName">

<form action="uploadservlet" enctype="multipart/form-data" method="POST">

<input type="text" name="CategoryName">
<input type="file" name="txtImgName"><br>
<input type="Submit" value="Upload File"><br>

</form>

public class Commonsfileuploadservlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private static final String TMP_DIR_PATH = "c:\\tmp";
    private File tmpDir;
    private static final String DESTINATION_DIR_PATH = "/files";
    private File destinationDir;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        tmpDir = new File(TMP_DIR_PATH);
        tmpDir.getName();
        System.out.println("inside 0124 init function##########    " + tmpDir.getName());
        if (!tmpDir.isDirectory()) {
            System.out.println("inside 1111111111");
            throw new ServletException(TMP_DIR_PATH + " is not a directory");
        } else {
            System.out.println("tmpDir.isDirectory() is directory......");
        }

        System.out.println("after 22222#########");
        String realPath1 = getServletContext().getRealPath(DESTINATION_DIR_PATH);
        System.out.println("realpath 111111111 - > " + realPath1);
        String realPath = "d:\\tmp";

        System.out.println("after 3333######### real path" + realPath);
        destinationDir = new File(realPath);
        System.out.println("after 444#########");
        if (!destinationDir.isDirectory()) {
            System.out.println("insideeeeeeeee");
            throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
        } else {
            System.out.println("not directry again***********");

        }
        System.out.println("after destination#########");

    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String test="";
        test=request.getParameter("temptest");
        System.out.println("test---- > "+test);
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
        /*
         * Set the temporary directory to store the uploaded files of size above threshold.
         */
        fileItemFactory.setRepository(tmpDir);

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        try {
            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
                } else {
                    //Handle Uploaded files.
                    out.println("Field Name = " + item.getFieldName()
                            + ", File Name = " + item.getName()
                            + ", Content type = " + item.getContentType()
                            + ", File Size = " + item.getSize());
                    String catadd = "s" + "16" + ".png";
                    //  File file = new File(destinationDir, item.getName());
                    File file = new File(destinationDir, catadd);
                    item.write(file);
                    System.out.println("File write successfullyYYYYYY...0201.....###################");
                }
                out.close();
            }
        } catch (FileUploadException ex) {
            log("Error encountered while parsing the request", ex);
        } catch (Exception ex) {
            log("Error encountered while uploading file", ex);
        }

    }

in above servlet i m not able to get "CategoryName" value of jsp input box.but when i remove <enctype="multipart/form-data"> like :
<form action="Commonsfileuploadservlet" method="POST">

then i get the "CategoryName" value.can anyone please suggest me what thing i m missing?

thanks Ashwani









Related Pages:
form based file upload using servlets
form based file upload using servlets  Hai all, I wrote a program to upload a file into specified directory and store the file path and username... used commons-fileupload and commons-io APIs. while i enterd username and upload
How to Upload a file directly to Oracle database using JSP or Servlets?
How to Upload a file directly to Oracle database using JSP or Servlets?  Hi I want to upload a file(csv or excel) to Oracle 10g Database using JSP...;Upload File to Oracle Database</h2> <form id="form1" enctype
Multiple file upload - Struts
Multiple file upload  HI all, I m trying to upload multiple files... need to upload is dynamically generated. I have tried using formfile. and also... only with servlets and i m using struts. I have this implemeted in servlets
Upload CSV File into Columns of sql table using servlets and jsp
Upload CSV File into Columns of sql table using servlets and jsp  Hello sir, plz give me the code to upload csv file data into respective columns of table
servlets
authentication HTTP digest authentication HTTPS client authentication Form-based... a PKC (Public Key Certificate). This verifies the browsers identity. Form-based authentication In FORM-based the web container invokes a login page. The invoked
file upload using JSP
file upload using JSP  I have created a form to upload a file...="java" %> <HTML> <HEAD><TITLE>Display file upload form... To Upload:</b></td> <td><INPUT NAME="file" TYPE="file"><
upload file and insert other details to database using a single form
upload file and insert other details to database using a single form   hi.. I have problem with uploading a file and insert other user datas together which I retrieved from another jsp/html page. Here i was able to upload file
Spring 3 MVC File Upload, Spring MVC File Upload
Spring 3 MVC File Upload Creating file upload example using Spring 3 MVC Learn how to create file upload application using Spring MVC module of the Spring... upload example using Spring 3.0 MVC module. In this tutorial we are creating file
How to upload file using JSP?
How to upload file using JSP?   Hi all, I m the beginner in JSP, I want to upload file on server in specific folder.   1)page.jsp... file upload form to the user</TITLE></HEAD> <
AJAX file upload
You need to create a form with file fields you wish to upload and define... for seeking file in local directory to upload file using this JavaScript plug... AJAX file upload If you want to upload file asynchronously means without
How to browse and upload the file in same page using jsp.
How to browse and upload the file in same page using jsp.  Hi Sir, I am doing a project in jsp servlets and i want to browse and upload...; <Html> <HEAD><TITLE>Display file upload form to the user<
Based on struts Upload - Struts
Based on struts Upload  hi, i can upload the file in struts but i want the example how to delete uploaded file.Can you please give the code
Servlets and
Servlets and   Sir...! I want to insert or delete records form oracle based on the value of confirm box can you please give me the idea.... thanks
File upload - JSP-Servlet
in the problem part]   Hi friend, Display file upload form to the user File Uload Using JSP   Choose the file To Upload... to do a file upload part. For this, i designed two files one for input and other
servlets
servlets  How to open and read the contents of a text file in servlets?   Please visit the following link: Read text file using Servlet
Struts 2 File Upload
Struts 2 File Upload       In this section you will learn how to write program in Struts 2 to upload the file... be used to upload the multipart file in your Struts 2 application. In this section you
Spring 2.5 MVC File Upload
easily create file upload and form based application in Spring MVC... Spring 2.5 MVC File Upload       Spring 2.5 MVC File Upload This tutorial explains how to upload
How I Upload File and Store that file name in Database using JSP
How I Upload File and Store that file name in Database using JSP  Hi All, I m the beginner in JSP and I want to upload the file and store that file... form like Emp name, Emp id, city, address and one employee profile image(upload
servlets
servlets  hi i am using servlets i have a problem in doing an application. in my application i have html form, in which i have to insert on date.... and it was in the form of string. so my question is, how to convert that string value
servlets
the cookie information using the HTTP request headers. When cookie based session... regarding the user usage and habits. Servlets sends cookies to the browser client using the HTTP response headers. When client gets the cookie information it?s
Java FTP file upload example
; Hi, We have many examples of Java FTP file upload. We are using Apache FTPClient for creating FTP based program in Java. See the complete list of FTP...Java FTP file upload example  Where I can find Java FTP file upload
servlets
of filters. A filter is configured in a web.xml file. The class using... functionality to the servlets apart from processing request and response paradigm..., in the order they appear in web.xml file. A filter also has life cycle
file upload using spring - Spring
file upload using spring  How to upload a file in server using spring framework
servlets
much info appended as a query stream. GET puts the form values into the URL... can't send a file from the client to the server via doGet. doPost has no limit
file upload in jsp - Java Beginners
file upload in jsp  how to upload a file using jsp. my operating...: Display file upload form to the user UPLOAD THE FILE   Choose the file To Upload:   2
servlets
servlets  how can I run java servlet thread safety program using... { super.init(config); acct=new account(); try{ File r=new File(?count... destroy() { File r=new File(?counter?); try{ DataOutputStream dout=new
upload and download a file - Java Beginners
the following code: 1)page.jsp: Display file upload form to the user UPLOAD THE FILE   Choose the file To Upload...upload and download a file  how to upload a file into project folder
upload using youtube api - MobileApplications
upload using youtube api   sir, as u have asked for my question i m sending it again plz reply me.i want code for java based mobile application, that can take .3GP video file and upload it to youtube using youtube's APIs
file upload
file upload  how to recieve the uploaded file on the next jsp page for modification if its uploaded to the previous page using a from
Writing a file using servlets - JSP-Servlet
Writing a file using servlets  I'm using a servlet to read an input from a jsp file and write into a .txt file in my computer. The code is good until reading the data and creating a file in my space. but it is not writing
tutorial for file upload in spring - Spring
tutorial for file upload in spring  Is there tutorial available for uploading file using spring framework. The example in the spring reference uses...; fileuploadform.jsp file Upload a file please Please upload a file
How i upload file and save that record in database using JSP?
How i upload file and save that record in database using JSP?  Hi All, I m the beginner in JSP and I want to upload the file and store that file and some other form data in MySQL database. Ex. There is one employee detail form
Upload csv or .xlsx file from JSP form to Database Table using servlet
Upload csv or .xlsx file from JSP form to Database Table using servlet  dear sir, i need the Servlet code that reads the .xlsx or CSV excel file... to Submit My Project i am using following code which is Working for .xls Excel file
image upload
of file on website using jsp and servlet but the condition is that the file should... in oracle or my sql. kindly help me.   JSP Upload file and save file path to database The given code allow the user to browse and upload selected file
Imge upload
;HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>...Imge upload  how to upload image in jsp.I am using Glassfish server...;td><b>Choose the file To Upload:</b></td> <td><
File Upload is working in FireFox & Chrome but not in IE7 using java & jquery
File Upload is working in FireFox & Chrome but not in IE7 using java & jquery  Hi, I have a form which is called on my button click "Upload a file... works fine at FireFox & Chrome,but when I tried to upload the file from Internet
Ajax File Upload Example
Ajax File Upload Example       This application illustrates how to upload a file using... HTML form for file upload Set the target to an iFrame which is on the actual
Upload image
" %> <HTML> <HEAD><TITLE>Display file upload form...; </tr> <tr> <td><b>Choose the file To Upload:</b><...;<b>You have successfully upload the file:</b> <% out.println
upload a image
;&lt;HEAD>&lt;TITLE>Display file upload form to the user&lt...;&lt;tr>&lt;td>&lt;b>Choose the file To Upload:&lt...;&lt;b>You have successfully upload the file by the name of:&lt;/b>
Struts2.2.1 file upload Interceptor example.
Struts2.2.1 file upload Interceptor example. In this example, we will disscuss about the file Upload Interceptor. Here, we are using a struts2.2.1 file tag  for uploading a file. Struts2.2.1 utilizes the services of File Upload
upload and save the file
upload and save the file  upload and save a file from a computer to specific location of remote computer using jsp
How to browse and upload the file in same page using jsp.
How to browse and upload the file in same page using jsp.  Hi, I am doing a project and i want to browse and upload the file in same page inside...; <HEAD><TITLE>Display file upload form to the user</TITLE><
jsp upload file to server
jsp upload file to server  How to create and upload file to server in JSP?   Find the given example that explains how to upload single and multiple file on server using JSP
upload image
upload image  how can i retreive image from mysql using jsp...); if ((contentType != null) && (contentType.indexOf("multipart/form-data..., formDataLength); totalBytesRead += byteRead; } String file = new String
Spring alternative to Form Based Login
. Using a login form we can use the jspringsecurity_check. How can we do it by sending a web service call and not using any form based authentication...Spring alternative to Form Based Login  print("code sample");how can
servlet file upload
servlet file upload  please tell me the complete code to upload a file on localhost using servlet
How to create d db for upload files using bolb i m followin dat upload file in db tutorial
How to create d db for upload files using bolb i m followin dat upload file in db tutorial  How to create d db for upload files using bolb i m followin dat upload file in db tutorial   Create a table named 'file
upload a file - Framework
upload a file  Hi to All, I need to upload a file from the client and that upload file should be sent to our co., mail please if any one provide.... Thankyou in Advance.  Hi friend, For upload a file in JSP visit
PHP code for csv file upload into mysql
PHP code for csv file upload into mysql  I want to upload a file from my pc to mysql server using upload option. while i m selecting the csv file...="file" id="userfile"> </td> <td width="80"><input name="upload
Struts upload file - Framework
Struts upload file  Hi, I have upload a file from struts application.I am able to get the file name using getFileName() i created excel file and send to file upload struts..how to get the sheets and data in that sheets

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.