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 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 Tutorials/Questions & Answers:
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
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
Advertisements
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
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
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"><
file upload using spring - Spring
file upload using spring  How to upload a file in server using spring framework
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
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> <
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
how to upload file using FTP in java
how to upload file using FTP in java  hai, i want to upload file using FTP in java Webservices.. Tel me some Articles Regards Asha
ModuleNotFoundError: No module named 'django-tastypie-with-file-upload-and-model-form-validation'
named 'django-tastypie-with-file-upload-and-model-form-validation'...-with-file-upload-and-model-form-validation After the installation of django-tastypie-with-file-upload-and-model-form-validation python library
ModuleNotFoundError: No module named 'django-tastypie-with-file-upload-and-model-form-validation'
named 'django-tastypie-with-file-upload-and-model-form-validation'...-with-file-upload-and-model-form-validation After the installation of django-tastypie-with-file-upload-and-model-form-validation python library
Unable to upload a file to mysql database using struts1
Unable to upload a file to mysql database using struts1  Hi, Below..." %> <html:html> <body> <html:form action="upload" enctype="multipart/form-data"> Select a File :<html:file property="file"/> <
upload a file and write it in JSP using servlet
upload a file and write it in JSP using servlet  Hello, I'm facing a problem here. I want to upload a file through abc.jsp and write the contents of file using a servlet in xyz.jsp. It is supposed to be a excel file which
how to update values of a html form into an excel table using java servlets?
how to update values of a html form into an excel table using java servlets?  i have written a java servlet program, which has a html form to be filled. after filling the form the servlet generates a receipt and the values should
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
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
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<
read XML file and display it using java servlets
read XML file and display it using java servlets  sir, i can't access Xml which is present in my d drive plz can u should go through my code n tell me the things where i went wrong java servlet program protected void
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
form field mapping with pdf file using java
form field mapping with pdf file using java   Hai all, I have one requirement that i have one html form.i have to map the form fields with pdf file. means, if click on text field according that perticular field .the data
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><
how do i upload a file by using servlet or jsp?
how do i upload a file by using servlet or jsp?  hi plz tell me the write java code
File Upload in J2ee on solaris machine using sftp - JSP-Servlet
File Upload in J2ee on solaris machine using sftp  Hi, Currently we are using FTP to upload the file from our J2EE web application... the application in such a way that file upload can be done using SFTP on remote Solaris
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
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
File Upload
File Upload  when i execute the image upload to mysql database it shows an exception that file path cannot be found
AJAX file upload
Description You need to create a form with file fields you wish to upload... and browse button for seeking file in local directory to upload file using... AJAX file upload If you want to upload file asynchronously means without
Sava data from Form to XML file using strutrs
Sava data from Form to XML file using strutrs  I'am a biginner with struts want so save data from my form in an Xml file using struts but i'm searching witout finding a solution thanks fo your help
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... wht u have posted, still der is some problem,My program creates class file, But whn i run d application it only uploades the file in C:/uploadedfiles, and i get
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 get xml file form http port using web service
How to get xml file form http port using web service  hi I am suresh i am using netbeans 6.9 to develop a web service for getting xml from http port and use the xml data to convert it to java file and store it to DB. But i am
How to save form data to a csv file using jquery or ajax
How to save form data to a csv file using jquery or ajax  Please let...=data.responseText; Now the problem is ,i should write form data to a csv file using ajax... this. i am able to read the csv file using this code if (window.XMLHttpRequest
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 save html form data into .csv file using only jsp.
how to save html form data into .csv file using only jsp.  Dear all, I am developing a website only using jsp and html. i need to save the form data into a .csv file using jsp. can anyone give me any sample solution or tutorial
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
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
File Upload
File Upload  Hi I need script / string in PHP where I uploaded the file in html frontend and it should sent the uploaded file as attachment to my email address
Ajax File Upload Example
Ajax File Upload Example       This application illustrates how to upload a file using... Create a simple HTML form for file upload Set the target to an iFrame which
File Upload in Struts.
File Upload in Struts.  How to do File Upload in Struts
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
Upload file to MS Access
Upload file to MS Access  Iam beginner and need to upload file to msaccess using jsp . Iam using netbeans platform. Kindly explain do I need to mention Attachment format in the table
servlet file upload
servlet file upload  please tell me the complete code to upload a file on localhost using servlet
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
zip file upload in php - WebSevices
zip file upload in php  This is not a normal upload. we know the code for normal upload. i need the zip file upload code in php. how to upload zipfile using php? and how to unzip using php? please i dont
Copy text file in a HTML form.
Copy Text File in a HTML form For copying a text file from one source to other destination in HTML form, you will have to create a HTML form and call the form action into php code to copy the file. In PHP code, first begin the PHP tag
HTML File Upload
HTML File Upload       HTML File Upload is used to show the list of all file, when a user click... with type="file". This involve one or more files into the submission of form
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
upload video using php
upload video using php  How to upload a video on MYSQL Server using PHP Code..? Can any one provide me an example
File upload - JSP-Servlet
----------------------------------------------------------------------------- Display file upload form to the user <% // for uploading the file we used Encrypt type of multipart/form-data and input...File upload  I am trying to do a file upload program. But, it shows

Ads