Uploading file in servlet from a html form

Uploading file in servlet from a html form

Sir,

I want to upload a picture from my html file and save it to my database as BLOB,but what JAR should i use for this purpose i am really confused about.And also is it possible to do this process without using a third party JAR, just using Java API.

please help me with this.

Thank You Ravi prakash

View Answers

March 5, 2012 at 11:04 AM

1)page.jsp:

<%@ page language="java" %>
<HTML>
<FORM ENCTYPE="multipart/form-data" ACTION="../UploadServlet" METHOD=POST>
<center>
<table border="0" bgcolor=#ccFDDEE>
<tr>
<center><td colspan="2" align="center"><B>UPLOAD THE FILE</B><center></td>
</tr>
<tr><td colspan="2" align="center"> </td></tr>
<tr><td><b>Choose the file To Upload:</b></td>
<td><INPUT NAME="file" TYPE="file"></td>
</tr>
<tr><td colspan="2" align="center"> </td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Send File"> </td></tr>
<table>
</center>
</FORM>
</HTML>

2)UploadServlet.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class UploadServlet extends HttpServlet{ 
     public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
     response.setContentType("text/html");
     PrintWriter out = response.getWriter();

    String saveFile="";
    String contentType = request.getContentType();
    if((contentType != null)&&(contentType.indexOf("multipart/form-data") >= 0)){
    DataInputStream in = new DataInputStream(request.getInputStream());
    int formDataLength = request.getContentLength();
    byte dataBytes[] = new byte[formDataLength];
    int byteRead = 0;
    int totalBytesRead = 0;
    while(totalBytesRead < formDataLength){
    byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
    totalBytesRead += byteRead;
   }
    String file = new String(dataBytes);
    saveFile = file.substring(file.indexOf("filename=\"") + 10);
    saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
    saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
    int lastIndex = contentType.lastIndexOf("=");
    String boundary = contentType.substring(lastIndex + 1,contentType.length());
    int pos;
    pos = file.indexOf("filename=\"");
    pos = file.indexOf("\n", pos) + 1;
    pos = file.indexOf("\n", pos) + 1;
    pos = file.indexOf("\n", pos) + 1;
    int boundaryLocation = file.indexOf(boundary, pos) - 4;
    int startPos = ((file.substring(0, pos)).getBytes()).length;
    int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
    File ff = new File(saveFile);
    FileOutputStream fileOut = new FileOutputStream(ff);
    fileOut.write(dataBytes, startPos, (endPos - startPos));
    fileOut.flush();
    fileOut.close();
    out.println("You have successfully upload the file:"+saveFile);
    Connection connection = null;
    String connectionURL = "jdbc:mysql://localhost:3306/test";
    ResultSet rs = null;
    PreparedStatement psmnt = null;
    FileInputStream fis;
    try{
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    connection = DriverManager.getConnection(connectionURL, "root", "root");
    File f = new File(saveFile);
    psmnt = connection.prepareStatement("insert into file(file_data) values(?)");
    fis = new FileInputStream(f);
    psmnt.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
    int s = psmnt.executeUpdate();
    if(s>0){
    System.out.println("Uploaded successfully !");
    }
    else{
    System.out.println("Error!");
    }
    }
    catch(Exception e){
        e.printStackTrace();
        }
    }
  }
}









Related Tutorials/Questions & Answers:
Uploading file in servlet from a html form
Uploading file in servlet from a html form  Sir, I want to upload a picture from my html file and save it to my database as BLOB,but what JAR should i use for this purpose i am really confused about.And also is it possible to do
File uploading - JSP-Servlet
File uploading  i am using file uploading code for multiple file and aslo for single file but i am getting problem that No such file found.... http://www.roseindia.net/jsp/file_upload/Sinle_upload.xhtml.shtml
Advertisements
FILE UPLOADING - JSP-Servlet
FILE UPLOADING  Hi , I want Simple program for file upload using html and servlet plese help me  hi friend pls try this code ********** try{ String type=""; String boundary=""; String sz
Using a image for Browse button instead of normal html Browse button for Uploading files from a JSP - JSP-Servlet
Using a image for Browse button instead of normal html Browse button for Uploading files from a JSP  I am using the following code snippet.... Is it not possible to use a image instead of normal html Browse button for uploading files
file uploading - JSP-Servlet
file uploading  Hi, thanks a lot for your kind answer. Now my program is running after I add the "servlet-api.jar" lib. Now, im facing another problem. Im not geeting the full output for the program. Even, the file
storing date from html form to oracle 10g using servlet
storing date from html form to oracle 10g using servlet  i have following html form from where date,month and year is retrieved separately.. <... this date month year from html form into oracle 10g database where i have
storing date from html form to oracle 10g using servlet
storing date from html form to oracle 10g using servlet  i have following html form from where date,month and year is retrieved separately.. <... this date month year from html form into oracle 10g database where i have
html and servlet file
servlet from html like this: <form method="post" action="http://localhost... html file with the jsp files amd servlet file insdie classes folder of tomcat. You...html and servlet file  where to place the html and the servlet class
Multiple file Uploading - JSP-Servlet
Multiple file Uploading   Hello everyone I am using jsp and my IDE... Submission Claim Submission Claim Form...() for servlet jsp threw exception org.apache.jasper.JasperException: Unable to compile
Uploading tha file - JSP-Servlet
Uploading tha file  hi,Sir. this is siddaiah. please give me response for the follwing questions. 1.how to upload file into oracle database using JSP? 2.How to upload photo into oracle database using JSP? Regards
html form - JSP-Servlet
html form  how to retrieve database value in dropdown list box placed in html form  Hi friend, Visit for more information. http://www.roseindia.net/jsp/ Thanks
java code for uploading a resume in a form - JSP-Servlet
java code for uploading a resume in a form  can anyone help me with the codes 4 uploading a resume in a registration form  Refer this link http://www.devsphere.com/mapping/docs/guide/upload.html Thanks Rajanikant
How to Open a File in HTML Form
How to Open a File in HTML Form  Hi, My question in that how could i open a file in HTML Form. Could any one suggest me the examples or online help... it. Otherwise take this examples and syntax that will show how to Open a file in HTML
'Hello World' file from a servlet (PDF, HTML or RTF).
 'Hello World' file from a servlet (PDF, HTML or RTF...; In this program we are going to tell you how we can create three file rtf,pdf and html... rtf,html or pdf)</b><br> <form action="
Sending form data from HTML page to SQLserver 2005 database by calling servlet code
Sending form data from HTML page to SQLserver 2005 database by calling servlet code  Hi sir, I would like to know how to send the form data from html page to database by calling servlet code from html page .   
calling java method from html form with out using javascript - JSP-Servlet
calling java method from html form with out using javascript  How can i call java method from a HTML form, java script should be disabled?  ...;script LANGUAGE="JavaScript">function testResults(form
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...,$destinationfile); } ?>  Draw the HTML form <!DOCTYPE HTML PUBLIC
Opening a file in a HTML form
Opening a file in a HTML form In this example, you will first see that a form has been created in HTML format and the code of opening a file has been written separately.  First create a HTML form and call the php action file to open
JSP:HTML Form in-place Editing - JSP-Servlet
JSP:HTML Form in-place Editing  I have an HTML form (form #1) which... from a stringquery into another page and having the same form, for some reason... beans. Perhaps you guys are better aware of in-place html form editing than me
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
Pass hidden veritable while uploading file - JSP-Servlet
way to pass hidden variables in request, from where we are trying to upload file... are uploading file, all the parameter other then file upload are null. Is it write... fields while uploading file on server?" Thanks in advance
JSP to add details to a database from a HTML form.
JSP to add details to a database from a HTML form.  Hi I'm a second year CS student who has to use JSP to validate a HTML form and add the details... from form and stores it in User--%> String Pword = request.getParameter
jsp or sevlet and html form to send picture to database - JSP-Servlet
that contains his picture to database. What I need are html page for the form that will browse for the picture, jsp or servlet that the info from html will go...jsp or sevlet and html form to send picture to database  Hello guys
JSP:HTML Form in-place Editing - JSP-Servlet
JSP:HTML Form in-place Editing  Hi, I want to thank the people... developer's needs. This is a follow up to the HTML Form in-place editing. The code... an excellent way of editing a form. I just have a few adjustments if any of you could
how to load values of html form into an excel table using java servlet?
how to load values of html form into an excel table using java servlet?   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
uploading a file
uploading a file  When I am trying to upload a file to another system in lan at a location "http://192.168.12.5:8080/tomcat-docs/myapps",then it is giving the following error message "http://192.168.12.5:8080/tomcat-docs/myapps
write to file from servlet - JSP-Servlet
write to file from servlet  Hi, I have a jsp file where I input data and retrive data through servlet. However; when I edit data it is not showing right data on the web site. I am also trying to write this data to file
how to fetch values from .properties to a html file
how to fetch values from .properties to a html file  I have a .properties file with some key value pairs in it. I need to fetch the values from this .properties file into a html file.Please let me know how to do
uploading image in the form
uploading image in the form  Hi All, I am working to build a form like railway registration form which accepts user id and password and image.../DisplayimageonJSPpageusingXML.shtml To know about file uploading using Struts2 you may go through the link, given
FORM Tag Correctly for Uploading Files.
a complete FORM tag for file uploading: How To Write the FORM Tag Correctly for Uploading Files? <?php print("<html><form action=file...FORM Tag Correctly for Uploading Files.  How To Write the FORM Tag
how to get a values from a multipart/form-data - JSP-Servlet
how to get a values from a multipart/form-data  Dear sir , I... ,matter,file field values but not status and from field i am getting null values and also the file is not uploading the content type in other jsp it is showing
file uploading
file uploading  How to upload music files onto the server and save the file information to the mysql database fetch and play the music files on a display page without download thus streaming the files
How to retrieve array values from html form to jsp?
How to retrieve array values from html form to jsp?  Hi! I am... it into jsp. Means i just want to retrieve values from html form containing array..., To get an array values from the html form you can use the getParameterValues
uploading audio file iphone
uploading audio file iphone  uploading audio file iphone
how to call servlet from html page at anchor tag ?
how to call servlet from html page at anchor tag ?  I have a very... and my website is running on it but after uploading it on server... to other page and at that place i give url of a servlet but in server that url
Data fetching from JSP or HTML - JSP-Servlet
Data fetching from JSP or HTML  Hi Deepak, Can u pls help me as i have a problem with jsp/html frameset. my question is how can i fetch the data from frameset which is in html format.pls help me. Thanks
if there is an invalid entry in html:file control then form is not submitting. - Struts
if there is an invalid entry in html:file control then form is not submitting.  Hi, I have used html:file to upload the files. this is working... the file then submit the form - form will submit without any problem 2) don't
query related to uploading file
query related to uploading file  hello friends i am doing my project in servlet and i want to upload a file and store file in local hard drive and file name and path in oracle database.with name file name and path i also want
Uploading an image - JSP-Servlet
and uploading is done by different jsp coding. I don't know how to code for file size... is not equal to Null and as well as the passed data from mulitpart/form-data...Uploading an image  I am doing a jsp project. In this uploading
how to pass form values from javascript of html page to jsp page
how to pass form values from javascript of html page to jsp page   This is my sample html page which contains inline javascript which calculates... to submit all the form values with lattitude and longitude returned from
Calling In JavaScript Functions from HTML Form To Validate User Entered Data
Calling In JavaScript Functions from HTML Form To Validate User Entered Data  Hello, I have been working for days on my web Form assignment and editing my html to call my functions to validate the user entered data
Uploading File on Server
Uploading File on Server  Hello, Can someone explain or suggest example. How do i uploading files on the FTP Server. Thanks
Uploading a file using UploadBean
Uploading a file using UploadBean  Dear sir, In my project i have to upload the file and use the same file for getting a values from that uploaded .xls file.I used UploadBean for uploading .For the first time when i
File Uploading Notification
File Uploading Notification  I am uploading files in my application and i want to know how can i know or be notified when file is uploaded. is there any file uploading event there which can tell me that process is going
Struts file uploading - Struts
Struts file uploading   Hi all, My application I am uploading... newDocumentForm = (NewDocumentForm) form; FormFile file... it is breaking while uploading the large file. Please let me know if you know any API
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... inserted into the excel file. 1)Create form.jsp <html> <body> <form
HTML Form data into .CSV?
HTML Form data into .CSV?  how to store data from html form to csvfile in java
How display a Image on Servlet from file upload - JSP-Servlet
How display a Image on Servlet from file upload  Dear Sir, My requirement is I want to display a Image on Servlet from File Upload. But It not display on servlet,Its appear a downloaded form and downloaded on disk when click
retrieving of value from excel file - JSP-Servlet
this message to all the employees when i upload a file then it fetch a data from... file so please help me how to take a parameter after uploading a file... Thanks...retrieving of value from excel file  Dear sir, Thanks for sending
retrieving of value from excel file - JSP-Servlet
this message to all the employees when i upload a file then it fetch a data from... file so please help me how to take a parameter after uploading a file...retrieving of value from excel file  Dear sir, Thanks for sending

Ads