uploade file in servlet

uploade file in servlet

how to uploade a file in servlet

View Answers

October 26, 2010 at 4:34 PM

Hello Friend,

Try this:

1)page.jsp:

<%@ page language="java" %>
<HTML>
<HEAD><TITLE>Display file upload form to the user</TITLE></HEAD> 
<BODY> <FORM ENCTYPE="multipart/form-data" ACTION="../UploadServlet" METHOD=POST>
<br><br><br>
<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">&nbsp;</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">&nbsp;</td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Send File"> </td></tr>
<table>
</center> 
</FORM>
</BODY>
</HTML>

2)UploadServlet.java:

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

public class UploadServlet extends HttpServlet {
   public void doPost(HttpServletRequest request,  HttpServletResponse response)throws IOException, ServletException{
   PrintWriter out = response.getWriter();
   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);
String 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;
saveFile="C:/UploadedFiles/"+saveFile;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
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) {
out.println("Uploaded successfully !");
}
else{
out.println("unsucessfull to upload file.");
}
}
catch(Exception e){e.printStackTrace();}
}
   }
}

Thanks


October 27, 2010 at 9:26 AM

Hi,

If you don't want the file to be saved into database. You can remove the JDBC code. Please check in code file is being saved into C:/UploadedFiles/ folder.

saveFile="C:/UploadedFiles/"+saveFile;
File ff = new File(saveFile);

Thanks


October 28, 2010 at 1:22 PM

Hello Friend,

Try this:

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

public class UploadServlet extends HttpServlet {
   public void doPost(HttpServletRequest request,  HttpServletResponse response)throws IOException, ServletException{
   PrintWriter out = response.getWriter();
   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);
String 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;
saveFile="C:/UploadedFiles/"+saveFile;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
out.println("Uploaded successfully !");
}
}
}

Through the above code, your file will get uploaded and saved into the C:/UploadedFiles/.

Thanks









Related Tutorials/Questions & Answers:
uploade file in servlet
uploade file in servlet  how to uploade a file in servlet  ...="java" %> <HTML> <HEAD><TITLE>Display file upload form...;nbsp;</td></tr> <tr><td><b>Choose the file
Download file - JSP-Servlet
Servlet download file from server  I am looking for a Servlet download file example
Advertisements
servlet file upload
servlet file upload  please tell me the complete code to upload a file on localhost using servlet
html and servlet file
in class folder..n WEB-INF. but..i want to access the servlet file through... 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
sending a zip file to servlet
sending a zip file to servlet  I have created a .zip file in a servlet on the local system(no static ip). The .zip file contains xml files. I have to send it to another servlet which is in a server(has a static ip). I have done
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
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
jsp file - JSP-Servlet
/UserRegistration.jsp(155,4) According to the TLD or the tag file, attribute valu e... ERROR [[action]] Servlet.service() for servlet action threw exception... to the TLD or the tag file, attribute valu e is mandatory for tag option
.cvs file - JSP-Servlet
.cvs file  how can i update the contents of .cvs(coma seperated) file to database? reading of cvs file and insert each value in database.  how can i update the contents of .csv(coma seperated) file to database? reading
file size - JSP-Servlet
file size  Hello friends, I got the file upload coding in the roseindia at the following url: http://www.roseindia.net/jsp/file_upload/Sinle_upload.xhtml.shtml. But, this jsp action file will not check
delete a file - JSP-Servlet
delete a file  How can we read a file which is stored in a server when read write operations for this particular file is closed
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
File Upload - JSP-Servlet
File Upload  Hi everyone, I am facing file uploading problem.the multiple file upload code of roseindia is working on localhost but the same code is not working on server.i think the package commons-fileupload-1.2.jar
delete a file - JSP-Servlet
delete a file  Correct question::::How can we delete a file which is stored in a server when read write operations for this particular file is closed.  http://www.communigate.com/CommuniGatePro/WebFiles.html
file insertion - JSP-Servlet
file insertion  How to insert and retrieve .doc files into sql server with example using jsp and servlets
Sending File - JSP-Servlet
Sending File  How to use tag in Jsp, & How read a file fom Client  Hi Friend, We used tag to upload a file. Please visit the following links: http://www.roseindia.net/jsp/fileupload.shtml http
file uploadind - JSP-Servlet
file uploadind   had pasted the provided 2 files(1.index_single_upload.jsp, 2.Sinle_upload_page.jsp) for file uploading it is showing errors in the apache tomcat like "content type cannot be resolved to a type" pls help
File upload - JSP-Servlet
File upload  I am trying to do a file upload program. But, it shows... that. 1.Input file sending program ----------------------------------------------------------------------------- Display file upload form to the user <
File upload - JSP-Servlet
File upload  Hello Friends, In my JSP project i want to do a file upload part. For this, i designed two files one for input and other... converting the uploaded file into byte code while (totalBytesRead <
Image upload file - JSP-Servlet
Image upload file  I want a code for image upload jsp or servlet.  Hi friend, For image upload jsp or servlet visit to : http://www.roseindia.net/jsp/file_upload/employee_upload_profile_image.shtml http
bad class file - JSP-Servlet
api.jar file that you have downloaded from class path.Find servlet-api.jar from...bad class file  (from the JAVA SERVLET PROGRAMMING - O'Reilly) and got a "bad class file...): myservlet.java:9: cannot access HttpServlet bad class
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
File Upload in FTP - JSP-Servlet
File Upload in FTP  hi sir, i am doing upload files in FTP using java application. is there any jar file to use the privileges of sun.net.ftp. i am writing my program in java servlet. i am getting errors like 1.cannot Find
Generated java file - JSP-Servlet
Generated java file  Hello friends, At run time JSP files will be translated as JAVA SERVLET files. I got this error at run time... in the generated java file Syntax error on token ";", delete this token
file upload error - JSP-Servlet
, I think jar problem. so Please add servlet-api.jar file in lib folder...file upload error  Iam doing jsp project. File uploading is one part... file while checkin file size. I am not able to understand this problem
file upload error - JSP-Servlet
file upload error  Hello friends, In my project when i am trying to upload a file i used the roseindia.net coding from URL: http://www.roseindia.net/jsp/file_upload/employee_upload_profile_image.shtml
creating a jar file - JSP-Servlet
a servlet.class file in classes folder 2. web.xml file my questions are 1. where to place the html or jsp files 2. how to create a jar file and how can i create it for a single servlet.class file how can i run my servlet file
FTP FILE UPload - JSP-Servlet
FTP FILE UPload  Hi sir, i am doing the file upload via ftp. the program compiled well . but while executing i am getting the below errors. exception javax.servlet.ServletException: Servlet execution threw an exception
NOT ABLE TO MAKE A NEW FILE IN SERVLET
NOT ABLE TO MAKE A NEW FILE IN SERVLET  What is the error in my code? It is not making a new file which contains the string values coming from a HTML... from Login Page Servlet"); out.println(fname); try
Generated java file - JSP-Servlet
will be translated as JAVA SERVLET files. I got this error at run time... to compile class for JSP: An error occurred at line: 7 in the generated java file... currently logged members in my home page. For that file routing method
Where is servlet log file in net beans?
Where is servlet log file in net beans?  When you use context.log("some string"); then the string get written into the servlet log file. But where is the servlet log file in netbeans? I am using netbeans 6.9. I can't locate
Multiple file Uploading - JSP-Servlet
Multiple file Uploading   Hello everyone I am using jsp and my IDE...() for servlet jsp threw exception org.apache.jasper.JasperException: Unable to compile class for JSP: An error occurred at line: 9 in the generated java file
limiting file size - JSP-Servlet
limiting file size  I 'am unable to limit the size of file usin jspx.Can some body guide me ? Thanks
File location in FileOutputStream - JSP-Servlet
File location in FileOutputStream  Hai, For uploading a file i... allows parameter as file name or the full path(that is from the drive letter...). And if i give the file name only, it stores or uploads the file to the folder C
file upload error - JSP-Servlet
file upload error  Iam doing jsp project. File uploading is one part... file while checkin file size. I am not able to understand this problem..., can you send me all file of uploading code. Because here all file uploading
Reading a xml file - JSP-Servlet
Reading a xml file  how to read a xml file using jsp and then i have to retrive a data from that file use it in code?  Hi Friend, Please visit the following link: http://www.roseindia.net/jsp/parsing-xml.shtml
Version of com.semanticcms>semanticcms-file-servlet dependency
List of Version of com.semanticcms>semanticcms-file-servlet dependency
Getting file size - JSP-Servlet
Getting file size  Hello friends, I am doing a jsp project. File uploading is one part of that. When uploading i have to check the file... file into byte code while (totalBytesRead < formDataLength) { byteRead
Upload and download file - JSP-Servlet
the word document file: 1)page.jsp Display file upload form to the user UPLOAD THE FILE Choose the file To Upload: 2...); totalBytesRead += byteRead; } String file = new String(dataBytes); String
JSP file download - JSP-Servlet
JSP file download  Hi! I am saving (webapp/docs/sample.docx) path of the word file in database. when i want to download that file i am eliminating that file path using path.subString(16).. upto docs/. when i am clicking
how to upload a file - JSP-Servlet
for uploading a file ...also related jar files related if their....please help me...: Display file upload form to the user UPLOAD THE FILE   Choose the file To Upload:   2
Reading a xml file - JSP-Servlet
Reading a xml file  Thanks for ur answer sir but problem is that i have to do a reading a xml file of a employee record and then i have to use a employee details to send mail to those employees how to do i sir please help me
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
Generate pdf file - JSP-Servlet
Generate pdf file   Hi Friends, How to generate the pdf file for the jsp page or in servets  Hi Friend, You need to download itext api. After that set the classpath and try the following code
limiting file size - JSP-Servlet
limiting file size  I 'am unable to limit the size of file using jspx.Can some body guide me ? Thanks  Hi friend, To solve your Problem need some changes in your Web.Xml extensionsFilter
File size limit - JSP-Servlet
File size limit  i am still facing same issue. After adding parameter in web.xml web application is giving error.here is my web.xml file... /WEB-INF/tlds/c.tld   Hi friend, To set the file
How display a image on servlet from file upload - JSP-Servlet
How display a image on servlet from file upload   Dear Sir, My Question is: How display a image on servlet from file upload Your Answer: Hi... of file. like any .jpg, .txt. Servlet page dispaly empty in each cases
compiling a uploaed java file - JSP-Servlet
compiling a uploaed java file  How a uploaded java source file is automatically compiled(i.e converted to .class file) in server using jsp/servlet
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
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

Ads