Home Answers Viewqa JSP-Servlet Changing loacation for file object

 
 


Jagadeesh
Changing loacation for file object
1 Answer(s)      2 years and 10 months ago
Posted in : JSP-Servlet

Hai,

For uploading a file i used the FileOutputStream() method. And uploading works perfectly. This method allows parameter as file name or the full path(that is from the drive letter. For example-->"C:/Program Files/Apache Software Foundation/Tomcat 6.0/webapps/mca2006sfssjc.co.in/stud/images/"+num+"."+ext) is required. Giving full path will not work in another machine. And if i give the file name only it stores or uploads the file to the folder C:\Program Files\Apache Software Foundation\Tomcat 6.0. Now, i ned a method to specify a location to store the file which is uploaded. I required to store the file at
C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\mca2006sfssjc.co.in\stud\images by changing the location to the folder images instead of giving this full path.

Thanks.
View Answers

July 23, 2010 at 12:52 PM


Hi Friend,

Try the following code:

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=
"uploadandstore.jsp" 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)upload.jsp:
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>

<%
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;

FileOutputStream fileOut = new FileOutputStream(saveFile);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
%><Br><table border="2"><tr><td><b>You have successfully upload the file by the name of:</b>
<% out.println(saveFile);%></td></tr></table>
<%
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("unsucessfull to upload file.");
}
}
catch(Exception e){e.printStackTrace();}
}
%>


Thanks









Related Pages:
Changing loacation for file object - JSP-Servlet
Changing loacation for file object  Hai, For uploading a file i used the FileOutputStream() method. And uploading works perfectly. This method allows parameter as file name or the full path(that is from the drive
changing Background Color
changing Background Color   ... change background color of a pdf file. You can change the background color... the object of Color by using new Color(0xFF, 0xFF, 0x00). We are passing three
changing the file content
changing the file content  I have requirement like this, a file... , reading the file content and changeing the 501 line content and crating one more file and storing this changeing information String line=null; String
Changing Executable Jar File Icon
Changing Executable Jar File Icon  I have created an executable jar file for my java program and the icon that appears is the java icon. I will like...;Hi, You may use JSmooth to create executable java file and also associate icon
Changing MySQL Port Number
Changing MySQL Port Number  How to change the MySQL port no in windows.   Hi, Open the my.ini file present in the MySQL server... to the desired port number. After making change in my.ini file save the file
Changing pictures - Java Beginners
Changing pictures  I found some html code that allows pictures to be changed on a web page. I copied the code and saved it as an html file. when I... Explorer that have pictures changing on them and they do not get blocked? 
How to save data to excel with a 2.1 work sheet format without changing it?
How to save data to excel with a 2.1 work sheet format without changing... and save it to excel file then read it again .. the problem is , when data is saved , the extension file is changed to excel file with text ( tab limited
loacation of errorpage in web.xml for 404 error
loacation of errorpage in web.xml for 404 error   The webpage cannot be found HTTP 404 Most likely causes: ā?¢There might be a typing error in the address. ā?¢If you clicked on a link, it may be out of date. What you
How to design a changing color of the chameleon, changing color of the chameleon, color of the chameleon
How to design a changing color of the chameleon       Have you seen the chameleon to changing...; Save File: Now go to File menu > Save optimized. Final Result
Changing column name
Changing column name      ... for changing the column name in the preparedStatement(). This will return the PreparedStatement object. The code of the program is given below
After changing url params d req checkboxes are not showing as clicked in jsf programming - Java Server Faces Questions
After changing url params d req checkboxes are not showing as clicked in jsf programming  Hi, Here i have Library.java file (collected from Jboss... Object state1; private Object state2; private Map getArtists
Java file object
Java file object This section demonstrates you the concept of File object... the programming much easier. Here we will discus the operations performed by File object. Using the File object, you can perform several operations. It parses
Object
Object       An object...). In an object, variables store values for later use and methods are the unit... are the basic units of the object-oriented programming. Objects are the part of our day
changing of data...
changing of data...  hi.... i have created a servlet page using a response.setheader(); method.in the parameter i have given 10 second.but once... is not changing in 10 second...what should i do..?? reply fast
changing of data...
data changing in 10 second  hi.... i have created a servlet page using a response.setheader(); method.in the parameter i have given 10 second.but... is not changing in 10 second...what should i do..?? reply fast
changing of data...
servlet.database is not changing in 10 second  hi.... i have created a servlet page using a response.setheader(); method.in the parameter i have... this servlet.database is not changing in 10 second...what should i do..?? reply fast
parsing XML file to get java object - XML
parsing XML file to get java object  Hello, I'm facing a problem in parsing XML file to get the java object. I've tried to retrieve data from XML file using SAX parser. my XML file structure is the following
File IO
are packaged into java.io. package. File Management with the help... are planning to learn file management using Java IO package.This class is available...; Constructing a File Name path Read the File
Changing the Name of Column in a JTable
Changing the Name of Column in a JTable   ... the name of column, you must have to change the column header. For changing the name... in JTable. For changing the name, you will need a table and column index that have
Object serialization - Java Beginners
them into a file using object serialization. Write another program to read that file, convert to Rupee if it reads a Dollar, while leave the value...Object serialization  Design classes for Currency, Rupee, and Dollar
Changing the Cursor in Java
Changing the Cursor in Java     ... cursor in java. Changing the cursor means showing cursor in many different ... the predefined cursor to set for the object. This method contains the Cursor
changing Chunk Color
changing Chunk Color     .... Code Description: In this Example we create the object... is a method of FontFactory. We are changing the color of the chunk
changing uiview background color
changing uiview background color  changing UIView background color in ios   self.view.backgroundColor = [UIColor colorWithRed:244.0f/255.0f green:230.0f/255.0f blue:183.0f/255.0f alpha:1.0f
Object Output Stream
Object Output Stream  Can anyone decode the data from a file which is written by ObjectOutputStream?? I want to know if this is a secure way to write protected data without encryption
Changing root Password
Changing root Password  how do i change the root password in mysql
NSMutableArray change object at Index
NSMutableArray change object at Index   NSMutableArray change object... to replace object, it's the best way to do that) for (int index = 0; index <... an array in its enumerate loop but because we don't remove/add an object to the array
how to add two object in a particular file - Java Beginners
how to add two object in a particular file  Hi frend.. I have two arraylist object in which there is some data..............now i want to add these two objects in a particular file using file handling in java....and also
object
object  is it possible to create object in the same class..?.   Yes, you can. class CreateObject { CreateObject(){ System.out.println("I have an object."); } public static void main(String[] args
OBJECT CLASS - Java Interview Questions
OBJECT CLASS  How To Find Out How many Objects Create?How Many Object Are Reachabule To Garbage Collector?i want Source code Plz Help me... variables holds without changing in all the instances
Changing 2D graph using slider.
Changing 2D graph using slider.  Code for changing a 2d graph with help of slider
changing selection color of <button>
changing selection color of   dear all, i have loaded image in border less button tag when button is selected with tab key i get brown color rectangle around image. how do i change color of that rectangle from brown to white
Problem in request Object
Problem in request Object  I have created a form where I have file input along with other inputs. I am using jsp to process the inputs. File input...; <td> <input type="file" name="file1" value
Deserializing an Object in java
or file. It takes a file name and then converts into java object. If any exception... of the FileInputStream class which holds the specified file object which has to be deserialized... Deserializing an Object in java     
Change a file timestamp
C:\vinod\Math_package>javac ChangeFileDate.java C:\vinod\Math_package>java ChangeFileDate Change file timestamp example! Enter file name with extension: StrStartWith.shtml Enter last
Problem in request object
Problem in request object  I have created a form where I have file input along with other inputs. I am using jsp to process the inputs. File input...;input type="file" name="file1" value="file1" size = 20 style="text-align:left
Object-Oriented Design - Overview
Java: Object-Oriented Design - Overview Background. Software development... the development of software on a sound foundation, but the field is changing fast enough... best practice is use of object-oriented approaches, using Object-Oriented
File location in FileOutputStream - JSP-Servlet
be used to store file object in a database column of data type "File". I need...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
Serializing an Object in Java
of saving an object in a storage medium (such as a file, or a memory buffer... a file name that is machine understandable and then serialize the object... Serializing an Object in Java   
getAttribute() Method Of The Request Object
getAttribute() Method Of The Request Object... for the illustration of the getAttribute() method of the request object in JSP... that is set through the setAttribute() method of the request object. The getAttribute
Request Object In JSP
provides two file for the best explanation about the request object in JSP... Request Object In JSP       This section illustrates more about the JSP implicit object called
swing application to import a object in a excel
swing application to import a object in a excel  Hi sir, I want to make a swing application where I can import a object in a cell of a excel... no will be inside java code) then go to: 'insert' ribbon>select 'object'>select
getQueryString() Method Of The Request Object
getQueryString() Method Of The Request Object... the getQueryString() method of the request object. Here, you will learn more... of the request object is used for getting the query string which is the values
removeAttribute() Method Of The Request Object
removeAttribute() Method Of The Request Object... for the method removeAttribute() of the request object. This method removes... the removeAttribute() method of the request object in JSP by learning through
Convert Object To XML
into xml file as child node values. Convert Object To XMLTo create a xml file pass the name of xml file with .xml extension into an object of FileOutputStream... Convert Object To XML      
MySQL Creating account and changing password
MySQL Creating account and changing password       This MySQL provide the new creating account... the password file to run make the /var/yp /directory after you make
Method is undefined for the type Object(org.apache.jasper.JasperException)
Method is undefined for the type Object(org.apache.jasper.JasperException) ... to compile class for JSP An error occurred at line: 413 in the jsp file: /jsps... getPracticeRevenueCode() is undefined for the type Object
Data Access Object
Creating Data Access Object (DAO) Design Pattern The Data Access Object.... It provides a technique to separate the object persistence and data access logic.... To make a Hibernate Dao at first you need to make hibernate.cfg.xml. This file
Changing Look and Feel of Swing Application
Changing Look and Feel of Swing Application       This section shows how to set different look...: This is the nested class of UIManager class. The object of this class returns the information

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.