Home Answers Viewqa JSP-Servlet to obtain image path

 
 


SHRUTI SHARMA
to obtain image path
3 Answer(s)      2 years and 7 months ago
Posted in : JSP-Servlet

i have made a web application in which you can upload a file and i have used File image = new File(image); here String image = request.getParameter("file"); and file is the name of FILESELECT button or BROWSE button . and i am expecting to obtain the complete path of the image from FILE that i have browsed but instead i m gettng just the name of the image.

this is my index.jsp page

<p>&lt;%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd"></p>

<p><html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
       &lt;FORM ACTION="upload" METHOD=POST>
            <br><br><br>
            <center><table border="2" >
                <tr>
                    <center>
                        <td colspan="2"><p align="center">
                                &lt;B>UPLOAD THE FILE</B>
                        </td>
                    </center>
                </tr>
                <tr>
                    <td>
                        <b>Choose the file To Upload:</b>
                    </td>
                    <td>
                        &lt;INPUT NAME="file" TYPE="file" value="">
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <p align="right">&lt;INPUT TYPE="submit" VALUE="Send File" ></p>
                    </td>
                </tr>
            </table>
            </center>
        </FORM>
    </body>
</html></p>

<p>and this is my servlet:upload.java
package controller;</p>

<p>import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;</p>

<p>public class upload extends HttpServlet {</p>

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
    PrintWriter out = response.getWriter();
    String imageUrl = request.getParameter("file");
    Connection connection = null;
    String connectionURL = "jdbc:mysql://127.0.0.1:3306/skill_tracker";
    ResultSet rs = null;
    PreparedStatement psmnt = null;


    // declare FileInputStream object to store binary stream of given image.

        try
        {                
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection(connectionURL, "root", "root");

            // create a file object for image by specifying full path of image as parameter.
            File image = new File(imageUrl);
            out.println(image);
            FileInputStream fis = new FileInputStream(image);
            psmnt = connection.prepareStatement("insert into pic values(?,?)");
            psmnt.setInt(1,'1');
            psmnt.setBinaryStream (2, (InputStream)fis, (int)(image.length()));
            /* executeUpdate() method execute specified sql query. Here this query
             insert data and image from specified address. */
            int s = psmnt.executeUpdate();
            if(s&gt;0) {
              out.println("Uploaded successfully !");
             }
            else {
           out.println("unsucessfull to upload image.");
              }
      }
     catch (Exception ex)
     {
        out.println("Found some error : "+ex);
     }
}

<p>}</p>
View Answers

October 29, 2010 at 11:15 AM


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="../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 29, 2010 at 6:18 PM


dat is very difficulto understand wat i have done is very simple...my code works on some system perfectly but on my system it has dis problm..if u can plz tell me waT can i do to get the complete path??


September 8, 2012 at 11:07 AM


Is it possible to do the same jsp function with php??? just curious...:-)









Related Pages:
to obtain image path
to obtain image path   i have made a web application in which you can... or BROWSE button . and i am expecting to obtain the complete path of the image from..."); // create a file object for image by specifying full path of image
Image name,image path into database and image into folder using jsp
Image name,image path into database and image into folder using jsp  How to insert image path and image name into oracle database and image into folder using jsp
Full path of image to save it in a folder
Full path of image to save it in a folder  Sir ,I am trying to upload... to find that image path &upload it as well. I am just a beginner in jsp...(p2.getContentType()); String type=sc.next(); try { String path
inserting an path of an image in database - JDBC
inserting an path of an image in database  hello kindly help related... to save it in folder..but can you plz tell me how an the full path of image can... an image using web cam.... and when the image is saved in a project at the same
how to insert the physical path of an image in database - JDBC
how to insert the physical path of an image in database  hello I m working in a project where we have to capture an image using web cam. when... path.. and also how to retrive that image path and show that picture in a small
i am inserting an image into database but it is showing relative path not absolute path
i am inserting an image into database but it is showing relative path not absolute path   hi my first page......... Image Enter your name: Upload photo: Father name: Age: Username: Password Qualification: Gender: Phone
i am inserting an image into database but it is showing relative path not absolute path
i am inserting an image into database but it is showing relative path not absolute path   hi my first page......... Image Enter your name: Upload photo: Father name: Age: Username: Password Qualification: Gender: Phone
i am inserting an image into database but it is showing relative path not absolute path
i am inserting an image into database but it is showing relative path not absolute path   hi my first page......... <html> <head> <title>Image</title> </head> <body bgcolor="lavender">
how to store image upload path to mssql database
how to store image upload path to mssql database  hi there!!, i need help in storing the image upload path into the database. basically i just use file select to upload the image from jsp to database. however when i click submit
how to store image upload path to mssql database
how to store image upload path to mssql database  hi there!!, i need help in storing the image upload path into the database. basically i just use file select to upload the image from jsp to database. however when i click submit
how to store image upload path to mssql database
how to store image upload path to mssql database  hi there!!, i need help in storing the image upload path into the database. basically i just use file select to upload the image from jsp to database. however when i click submit
how to store image upload path to mssql database
how to store image upload path to mssql database  hi there!!, i need help in storing the image upload path into the database. basically i just use file select to upload the image from jsp to database. however when i click submit
Java get Absolute Path
Java get Absolute Path       In this section, you will study how to obtain the absolute path... file.getAbsolutePath() returns the absolute path of the given file.    
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
pls provide common path to set image in flex - XML
pls provide common path to set image in flex  hi, pls provide common setpath to image in flex.when i give ful path like these C:\eclipse\workspace... the coding in mxml to set common path of image in flex
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 store user name,city,state,image path into database and image into folder using jsp
How to store user name,city,state,image path into database and image into folder using jsp  How to store user name,city,state,image path into database and image into folder using jsp
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 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 ... that your system does not find the image, you have specified.Set the path of an image...")); document.open(); Image image = Image.getInstance("C:/image2.png"); Image
How to store url path?
How to store url path?  Image is stored in physical directory like... path like this String file = "http://www.queen.com/website/screenshots/" + username + createTimeStampStr() + ".PNG"; this my program public class Image
Java IO Path
an image is given below : So, according to the above image the path (in windows... path. for example, to locate a xyz.txt file in the above image the absolute path... to be located. for example, to locate a xyz.txt file in the above image the relative path
How to store url path in file ?
How to store url path in file ?  Hi, How to store url path in file ? this my program public class Image implements Runnable..."; This is store phiscal directory but i want store url path like
image retreival
image retreival  I ve stored the path of image and audio in mysql database. how to retrive it and display... Can u pls help me out
Image retrieve
Image retrieve  HI.. store image path/data Java Coding. ... It's supposed to take the image, store it in a directory as well as pass the image path to mysql database... Now I want to retrieve the data from directory using path
storing images in directory,saving path in db2
storing images in directory,saving path in db2  i am working in a web... in a folder and its path(relative/absolute) in my DB2 database. and when the user logins, i shall retrieve the image and show it as the profile image again
browse image
browse image  how to browse the image in image box by browse button and save image in database by save button by swing   import java.sql.... java.awt.image.*; import java.awt.event.*; public class UploadImage extends JFrame { Image
browse image
browse image  how to browse the image in image box by browse button and save image in database by save button by swing   import java.sql.... java.awt.image.*; import java.awt.event.*; public class UploadImage extends JFrame { Image
Browse an image
Browse an image  hi................ i want to browse an image from... java.awt.event.*; public class UploadImage extends JFrame { Image img; JTextField... GridLayout(1,2)); JLabel label=new JLabel(); File file = null; String path=""; public
image in jsp - JSP-Servlet
image in jsp  i m storing path of image in my database.. but when i m trying to display image using that path image is not getting... i m storing path like c:\image\a.jpg ... and i m using tag... how to get
Display image
Display image  How to Pass image from html to jsp and display that image using jsp   Here is an example that pass an image path from...); } catch(Exception ex){ System.out.println("GET IMAGE PROBLEM : "+ex
image upload
image upload  Hello sir I want to upload image or any other type... be upload in the server and their path should be stored in database either in oracle or my sql. kindly help me.   JSP Upload file and save file path
How to retrieve file name and path of an excel spreadsheet imported into Oracle Database
table for each spreadsheet but I want to obtain the path and filename of each...How to retrieve file name and path of an excel spreadsheet imported into Oracle... Oracle database and I want to know how to retrieve the path of the file
How to get the full path location using <input type=file>
How to get the full path location using input type=file  Hi. I have used input type=file> in HTML to select an image. But it selects only the image but not with its full path location. how to do it? Thanks in advance
substitute image link
substitute image link  How can i display a substitute image if there is no image found? <Image Source="{Binding Path, FallbackValue... a default image or link in the image source file
Fetching image from database
Fetching image from database  I have uploaded image path and image name in database so, now how can i display that image using JSP or HTML page(is it possible to display using tag using concatination). image path i have stored
Clip of image
in an image. To give the path with straight line, we have used the class GeneralPath... Clip of image       In this section, you will studied how to show a clip of image
image upload in java
image upload in java  Hi, I am working with java. In my application i want to give facility to user to add and change image. I use open dialog box to select image, it will work properly i.e on button click open dialog is open
image save to folder in java
image save to folder in java  Hi, I am working with java. In my application i want to give facility to user to add and change image. I use open dialog box to select image, it will work properly i.e on button click open dialog
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..., for example, i need to save a image for the photo of candidate and resume
Image display in pdf
Image display in pdf  i am trying to display a image in pdf using xsl fo but " [ERROR] Error while creating area : Error with image URL: images\distilloginmedia\distillogo.png (The system cannot find the path specified
image on submit button
image on submit button  i need to set an image on submit button... url("path/to/image.jpg") 0 0 no-repeat; font-weight: bold; display...; /* height of the background image */ width: 500px; /* width of the background
Jmagick get image size
to get the image size when using Jmagick ImageInfo ii = new ImageInfo(path...Jmagick get image size  Hi, How I can get the image size while using...); Thanks,   hi, the code given below may help you to get the image
Interact with connection pools to obtain and release connections
Interact with connection pools to obtain and release connections Prev Chapter 4. Demonstrate understanding... to obtain and release connections Connection handles
image upload in webapp/upload folder
image upload in webapp/upload folder  sir i want to store upload image in my project directory WebApp/Upload_image/ pls send the jsp servlet code when i upload the image one error found "system cannot found the specified path
ZodiacSign with an image - Java Beginners
class ZodiacSign { protected static ImageIcon createImageIcon(String path...(path); if (imgURL != null) { return new ImageIcon(imgURL...: " + path); return null; } } public static void
struts image uploading
struts image uploading  please let me know how to upload image...=con.createStatement(); //String path = getServlet...(); outputStream = new FileOutputStream(new File(path
Regarding Image in Swings
Regarding Image in Swings  Hi, I have some requireemnt like when i click on the button in frame,it wil display the image.....plz do the needful... == JFileChooser.APPROVE_OPTION) { file = chooser.getSelectedFile(); String path
Path was not found
Path was not found  The Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path
path classpath
path classpath  EXPLAIN PATH AND CLASSPATH ? DIFF send me ans plz..., Path is system wide variable that tells where to find your commands. Lets... be in path. While Classpath is Enviroment Variable that tells JVM or Java Tools where
struts image uploading
struts image uploading  please let me know how to upload image...=con.createStatement(); //String path = getServlet...(); outputStream = new FileOutputStream(new File(path

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.