downloading file through a file's path stored in database in jsp

downloading file through a file's path stored in database in jsp

hi want to download a file from a directory where the file location is stored in a database,i have done the coding for retrieving the path from database to a html table,but i dont know hoe to download the file using its path stored in database.here is my code for retrieving the path from database.

<%@ page import="java.io.*,java.sql.*"%>


<%
String id=request.getParameter("id");
Class.forName("com.mysql.jdbc.Driver").newInstance();  
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ksa","root","root");  
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select id,file_path,file_date from file12 where id like '"+id+"%'");
  %>
 <table cellpadding="15" border="1">
 <%
  while(rs.next()){

 %>
 <tr>
<td><%=rs.getString("id")%> </td>
<td><%=rs.getString("file_path")%></td> 

<td><%=rs.getString("file_date")%> </td> 
  </tr>
  <%}%>
 </table>
View Answers

May 10, 2012 at 4:57 PM

JSP Upload and download file

The given code allow the user to choose the file and upload it and save the file path into database. Then retrieve the path of the file from database and display it on the browser. On clicking the particular link of file path, you will be able to download that file.

1)form.jsp:

<%@ page language="java" %>
<HTML>
<FORM ENCTYPE="multipart/form-data" ACTION="uploadFile.jsp" 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)uploadFile.jsp:

<%@ page import="java.io.*,java.sql.*,java.util.zip.*" %>
<%
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("C:/UploadedFiles/"+saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
%><br><table border="2"><tr><td><b>You have successfully upload the file:</b>
<%out.println(saveFile);%></td></tr></table>
<%
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/roseindia";
PreparedStatement psmnt = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "root");
psmnt = connection.prepareStatement("insert into file(file_path) values(?)");
psmnt.setString(1, ff.getPath());
int s = psmnt.executeUpdate();
if(s>0){
System.out.println("Uploaded successfully !");
}
else{
System.out.println("Error!");
}
Statement st=connection.createStatement();
ResultSet rs=st.executeQuery("Select file_path from file");
  %>
 <table cellpadding="15" border="1">
 <%
  while(rs.next()){

 %>
 <tr>
<td><a href="download.jsp?f=<%=path%>"><%=rs.getString("file_path")%></a></td> 
 </tr>
  <%}%>
 </table>
 <%
}
catch(Exception e){
    e.printStackTrace();
}

}
%>

May 10, 2012 at 4:58 PM

continue..

3)download.jsp:

<%@ page import="java.util.*,java.io.*"%>
<%@ page import="java.net.*"%>
<%!
public static String getMimeType(String fileUrl)
throws java.io.IOException, MalformedURLException
{
String type = null;
URL u = new URL(fileUrl);
URLConnection uc = null;
uc = u.openConnection();
type = uc.getContentType();
return type;
}

%>
<%
String file=request.getParameter("f");
File f = new File (file);
String filename=f.getName();
String type=getMimeType("file:"+file);

response.setContentType (type);
response.setHeader ("Content-Disposition", "attachment; filename=\""+filename+"\"");

String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length());
InputStream in = new FileInputStream(f);
ServletOutputStream outs = response.getOutputStream();

int bit = 256;
int i = 0;
try {
while ((bit) >= 0) {
bit = in.read();
outs.write(bit);
}
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
outs.flush();
outs.close();
in.close();
%>









Related Tutorials/Questions & Answers:
downloading file through a file's path stored in database in jsp
downloading file through a file's path stored in database in jsp  hi want to download a file from a directory where the file location is stored... table,but i dont know hoe to download the file using its path stored
How to browse excel file and stored the contents into the database using jsp/servlet?
How to browse excel file and stored the contents into the database using jsp/servlet?  Hi.. I want to browse excel file and stored the file data into the My-sql database using jsp/servlet
Advertisements
how to upload multiple files in jsp and saving the path in database and the file in folder
how to upload multiple files in jsp and saving the path in database and the file in folder  how to upload multiple files in jsp and saving the path in database and the file in folder I have created a form for the upload of files
how to display or retrive an image in jsp whose path is stored in oracle database
how to display or retrive an image in jsp whose path is stored in oracle database  how to display or retrive an image in jsp whose path is stored in oracle database and the image is stored in my pictures folder
how to store image in folder and stored image path in mysql database using JSP
how to store image in folder and stored image path in mysql database using JSP  how to store image in folder and stored image path in mysql database using JSP
how to read data from excel file through browse and insert into oracle database using jsp or oracle???
how to read data from excel file through browse and insert into oracle database using jsp or oracle???  sir.. i have number of excel sheets which...://www.roseindia.net/answers/viewqa/JSP-Servlet/28123-write-excel-file-into-the-oracle
To insert attachment file in database in JSP.
To insert attachment file in database in JSP.  I am doing project in JSP. How to insert attachment file in mysql database? Please suggest some solution. Your inputs is valuable to me.   Hi Friend, Visit HereADS
where this file is stored
where this file is stored  thank your sir, but where this file is stored? and how to get the path for further use
File path for jar file
File path for jar file  Hi Experts, I have created one eclipse... not found for the template file. Also I had tried to get that path from user... path of the template, which is working as per expectation. But I have created
Getting File path error - JSP-Servlet
Getting File path error  I have a requirement where i need to get certain properties on application login page start itself. I an currently using String str = request.getRealPath("/")+"a" + System.getProperty( "file.separator
To insert attachment file in database in JSP.
To insert attachment file in database in JSP.  I am doing project in JSP. How to insert attachment file in mysql database? Please suggest some... file upload form to the user</TITLE></HEAD> <BODY> <FORM
Retriving zip file stored in database into my own filesystem
Retriving zip file stored in database into my own filesystem  Hi all... several zip file stored in this table now I want to retrieve it and put it in an directory in my file system. PreparedStatement psmt=con.prepareStatement("select
Struts file downloading - Struts
Struts file downloading  how to download a file when i open a file from popup option like save ,open and cancel file is opened but file content is not showed even i check the file size also and generating excetion like
file upload and insert name into database - JSP-Servlet
file upload and insert name into database  Hi, I just joined as a fresher and was given task to upload a file and insert its name into database...  HIread for more information,http://www.roseindia.net/jsp/file_upload
How to retrieve file name and path of an excel spreadsheet imported into Oracle Database
Oracle database and I want to know how to retrieve the path of the file...How to retrieve file name and path of an excel spreadsheet imported into Oracle... table for each spreadsheet but I want to obtain the path and filename of each
i am getting the problem when i am downloading the pdf file from oracle 10g database - Struts
i am getting the problem when i am downloading the pdf file from oracle 10g... into datbase and download the pdf file from database. but when i created the pdf file..., Please go through the following link: http://www.roseindia.net/jsp
How to create file and save it into user defined path using jsp/servlet?
How to create file and save it into user defined path using jsp/servlet?  Hi.. Onclick event I have created one file.When file will create it should asked where to save file(like browse option
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 and some other form data in MySQL database. Ex. There is one employee detail
To call jrxml/jasper file through jsp code in netbean
To call jrxml/jasper file through jsp code in netbean  I am making web application in jsp with netbean. For report I am using ireport 3.6.7.... my question is I want to call that jasper file through my jsp code and i also
use properties file to connect to the database in jsp..
use properties file to connect to the database in jsp..  How to use properties file to connect jsp code with database ..........   Here is a jsp code that connects to database using properties file. <%@page import
PHP hide file path
PHP hide file path  PHP to read a path and convert that to the virtual link
urgent need for jsp code with mysql query for uploading and downloading file - JSP-Servlet
urgent need for jsp code with mysql query for uploading and downloading file  can anyone tell me how to upload and download a doc file using jsp with mysql as the back end... and kindly help me to create the table too
common database jsp file for all the jsp files in the application
common database jsp file for all the jsp files in the application  hi... use of this single jsp file while connecting to database rather than writing connectivity code in all the jsp pages . send me the code for that . thanks
jsp-file
jsp-file  i want to upload a file by browse button and the file should be save in ms access database.....how i can implement trough jsp plz help me sir
how to display data from jsp file into database
how to display data from jsp file into database  this is a jsp file . look at the line with code-> Statement st=con.createStatement...+",'"+email+"')"); out.println("Data is successfully inserted into database
JSP File
JSP File  Hi, What is JSP File? How to create JSP file? Thanks   Hi, JSP file is simple text file with .jsp extenstion. You can run JSP file on tomcat server. Read more at JSP tutorials section. Thanks
passing values between jsp file through hyperlink in div tag
passing values between jsp file through hyperlink in div tag  <...;script src="js/AdminHeader.js"&gt;&lt;/script&gt; &lt;jsp:include page="/jsp/admin/Adminmenu.jsp" &gt; &lt;/jsp:include&gt
To Upload and insert the CSV file into Database
to upload a CSV file through JSP and insert it into the database. For this, we have... To Upload and insert the CSV file into Database... content of file into String. To insert this file into the database, write
database through jsp
database through jsp  sir actually i want to retrieve the data from database dynamically.because i dont know how many records are there in the database? thanks   Here is an example of jsp which retrieves data from
Storing content from file path to an array
would like to access the "Animation.txt" file from this path and store the contents in this text file to an array. I am using jsp. I can access my path but how...Storing content from file path to an array  Hi, I have a path
ModuleNotFoundError: No module named 'file-path'
ModuleNotFoundError: No module named 'file-path'  Hi, My Python... 'file-path' How to remove the ModuleNotFoundError: No module named 'file... have to install padas library. You can install file-path python with following
Read data from excel file and update database using jsp
Read data from excel file and update database using jsp  read data from excel file and update database using jsp Hi, I am using a MySQL database... upload excel file and update database using JSP ? Thanks in Advance
Constructing a File Name path in Java
is helpful for mapping local  file name with the actual path of the file using the constructing filename path technique. As you have seen, how a file... location The absolute path of the file is: C:\nisha\example\myfile.txt
Problem in getting file path in js
Problem in getting file path in js  hi, I am using ofbiz framework , How i can get the file path in javascript for input type = "file" and i am using only firefox not other browser. so please help me it is very important for me
Java file absolute path
("Absolute Path of the file is: " + absolutepath); } } Through...Java file absolute path In this section, you will learn how to get the absolute path of the file. Description of code: If you want to locate a file without
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
downloading a file directly from mysql using java
downloading a file directly from mysql using java  Hi, I am trying to come up with a code to download a file that is on a mysql database (in form of a blob) without using url. Can anyone tell me how it can be done because I am
how to get the image path when inserting the image into pdf file in jsp - JSP-Servlet
how to get the image path when inserting the image into pdf file in jsp  Hi Friend, my image path;C:/images/photo.jpg. i am getting the below error error: The type Image is ambiguous document.open(); Image
How to get path of a file in iOS?
How to get path of a file in iOS?  Hi iOS project I have added a file abg.jpg, Now I want to know the path of the image file when installed in iOS. Pl let's know the code. Thanks   Hi, You can use following code
run a batch file through javascript
run a batch file through javascript   How to run a batch file through javascript without prompting
HTML(Registration form) to Jsp to stored into MS ACCESS database
HTML(Registration form) to Jsp to stored into MS ACCESS database  i am sending one html file that contain 18 fields these are stored in ms-access database by using jsp code.i want to urgent jsp code. please urgent sir. thank
File Path compare in java
File Path Comparison :compareTo      File Path Comparison :compareTo In this section, we will discuss how to compare pathname of two file for the equality
Data needs to be gathered in XML file from the database (MySql) using JSP
data regarding particular id from the database table. Data needs to be gathered in XML file from the database (MySql) using appropriate JSP/Java Bean functions...Data needs to be gathered in XML file from the database (MySql) using JSP 
open pdf file in same jsp page and the pdf file should retrieved from database
open pdf file in same jsp page and the pdf file should retrieved from database  Hai all, I need code to open a pdf file in same jsp page(browser) while click on hyperlink And the file was located in database table. Can any
Java Construct File Path
Java Construct File Path In this section we will discuss about how to construct file path in Java. A file path can be constructed manually or by a Java program. It is best practice to construct a file path in Java by a Java Program
how to get the image path when inserting the image into pdf file in jsp - JSP-Servlet
how to get the image path when inserting the image into pdf file in jsp  I am using the below code but i am getting the error at .getInstance. i am... that your system does not find the image, you have specified.Set the path of an image
How to store url path in file ?
How to store url path in file ?  Hi, How to store url path in file... = robot.createScreenCapture(new Rectangle(1000,700)); String file = "C:/xampp..."; This is store phiscal directory but i want store url path like
written in jsp file
written in jsp file  how to create and write in a jsp file through simple core java code
File upload in JSP
into virtual path in the server or converting them into bytes and stored...File upload in JSP  hi! In my previous interview i got two questions which i could not answer regarding file upload and annotations. I want to know
Getting path name of uploading file in struts 2.8.1
Getting path name of uploading file in struts 2.8.1  Hai! I am using struts 2.8.1. I want to upload file into database with the path name. How can I can get the original path name of the file in struts 2.8.1? It only display

Ads