Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners uploade file in servlet
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


Neo Java Developer
uploade file in servlet
3 Answer(s)      4 years ago
Posted in : Java Beginners


how to uploade a file in servlet


Advertisement
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  ...;HTML> <HEAD><TITLE>Display file upload form to the user<...;</tr> <tr><td><b>Choose the file To Upload:</b>
servlet file upload
servlet file upload  please tell me the complete code to upload a file on localhost using servlet
Advertisements
Download file - JSP-Servlet
Servlet download file from server  I am looking for a Servlet download file example
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
.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
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 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
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
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
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
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
file insertion - JSP-Servlet
file insertion  How to insert and retrieve .doc files into sql server with example using jsp and servlets
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
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
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 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 <
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
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
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
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
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
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
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
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
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
Advertisements
 

 

 

DMCA.com