• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Uploading jpeg images to webserver

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Friends.,
This is my first post in this group. Hope you all will help me.
I'm doing project in JSP and Oracle and the webserver i'm using for testing is Apache Tomcat and Sun's AppServer.
Here in my project my module is Human Resource System. So for that i want to store the employee details. with their pictures.
I don't know how to upload the image file to the server so that i can create a folder named "images" inside my application and can store all the image files inside that..for example.. if there is 100 employees means. i want to upload all the 100 photos and also their details.
so for that i want to store the path and file name of the image file in the database also..

Any way...
Please help me friends.
Give me some ideas to do this and make my project successful

Thanks
regards
Sonu
 
Sheriff
Posts: 67746
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The JSP FAQ has an entry on uploading files.
 
Sonu Philip
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Bear Bibeault.,
Since i'm a beginner in JSP i couldn't understand much about that. So kindly please reply with some urls of file uploading for beginners or some tutorials or some examples also..

Thanks in advance
regards
Sonu!!
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Please check this code..hope u will gt idea.
create a jsp file(frontend) to upload the image
and create another file to store the image.

code.
--------
<%@ page language="java" import="java.io.*,java.sql.*,java.net.URLEncoder,java.util.*,javax.servlet.*,javax.servlet.http.*,javax.servlet.jsp.JspWriter" %>
<html>
<body bgcolor="#FFFFFF" text="#660033" background="" bgproperties=fixed>
<%!private String UploadFile(String s, String s1, String s2, ServletInputStream servletinputstream, String s3)
throws ServletException, IOException
{
System.out.println("Into UploadFile method");
Object forLock1 = new Object();
String newline = "\n";
String s6 = null;
String s7 = "";
byte abyte0[] = new byte[4096];
byte abyte1[] = new byte[4096];
int ai[] = new int[1];
int ai1[] = new int[1];
long l = 0L;
String s8 = getId();
String s4;
while((s4 = readLine(abyte0, ai, servletinputstream, s3)) != null)
{
int i = s4.indexOf("filename=");
if(i >= 0)
{
s4 = s4.substring(i + 10);
i = s4.indexOf("\"");
if(i > 0)
s4 = s4.substring(0, i);
break;
}
}
if(s != null)
s4 = s;
s7 = s4;
if(s7 != null)
{

s7 = getFileName(s7);
String s5 = readLine(abyte0, ai, servletinputstream, s3);
if(s5.indexOf("Content-Type") >= 0)
readLine(abyte0, ai, servletinputstream, s3);
File file = new File(s1, s8);
FileOutputStream fileoutputstream = new FileOutputStream(file);
while((s5 = readLine(abyte0, ai, servletinputstream, s3)) != null)
{
if(s5.indexOf(s2) == 0 && abyte0[0] == 45)
break;
if(s6 != null && l <= 75L)
{
fileoutputstream.write(abyte1, 0, ai1[0]);
fileoutputstream.flush();
}
s6 = readLine(abyte1, ai1, servletinputstream, s3);
if(s6 == null || s6.indexOf(s2) == 0 && abyte1[0] == 45)
break;
fileoutputstream.write(abyte0, 0, ai[0]);
fileoutputstream.flush();
}
byte byte0;
if(newline.length() == 1)
byte0 = 2;
else
byte0 = 1;
if(s6 != null && abyte1[0] != 45 && ai1[0] > newline.length() * byte0)
fileoutputstream.write(abyte1, 0, ai1[0] - newline.length() * byte0);
if(s5 != null && abyte0[0] != 45 && ai[0] > newline.length() * byte0)
fileoutputstream.write(abyte0, 0, ai[0] - newline.length() * byte0);
fileoutputstream.flush();
fileoutputstream.close();
try
{
synchronized(forLock1)
{
File file1 = new File(s1, s7);
try
{
file1.delete();
}
catch(Exception _ex) { }
file.renameTo(file1);
}
}
catch(Exception _ex) { }
} else
{
throw new IOException();
}
return s7;
}

%>
<%! private Hashtable getConfig(String s)
{
Hashtable cfgs = new Hashtable();
Hashtable hashtable;
if(s != null)
hashtable = (Hashtable)cfgs.get(s);
else
hashtable = getDefaultConfig();
if(hashtable != null)
if(s != null)
{
String s1 = (String)hashtable.get("edited");
File file = new File(s);
if(file == null)
cfgs.remove(s);
else
if(!s1.equals(String.valueOf(file.lastModified())))
cfgs.remove(s);
else
return hashtable;
} else
{
return hashtable;
}
hashtable = new Hashtable();
readConfig(hashtable, s);
cfgs.put(s, hashtable);
return hashtable;
}
%>
<%!private Hashtable getDefaultConfig()
{
Hashtable hashtable = new Hashtable();
hashtable.put("dir", "/photos");
hashtable.put("edited", "");
return hashtable;
}

private String getFileName(String s)
{
int i = s.lastIndexOf("\\");
if(i < 0 || i >= s.length() - 1)
{
i = s.lastIndexOf("/");
if(i < 0 || i >= s.length() - 1)
return s;
}
return s.substring(i + 1);
}
%>
<%!private String getId()
{
int HOW_LONG = 6;
String s = "";
Object SessionIdLock = new Object();
synchronized(SessionIdLock)
{
long l = System.currentTimeMillis();
Random random = new Random();
s = String.valueOf(l);
for(int i = 1; i <= HOW_LONG; i++)
s = s + (int)(1.0D + (double)HOW_LONG * random.nextDouble());

}
return s;
}
%>
<%!private void readConfig(Hashtable hashtable, String s)
{
try
{
BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(new FileInputStream(s)));
String s1;
while((s1 = bufferedreader.readLine()) != null)
{
s1 = s1.trim();
if(s1.length() > 0)
{
int i = s1.indexOf("=");
if(i > 0 && i < s1.length() - 1 && s1.charAt(0) != '#' && !s1.startsWith("//"))
hashtable.put(s1.substring(0, i).trim(), s1.substring(i + 1).trim());
}
}
bufferedreader.close();
File file = new File(s);
hashtable.put("edited", String.valueOf(file.lastModified()));
}
catch(Exception _ex) { }
String s2;
if((s2 = (String)hashtable.get("port")) != null)
try
{
int j = Integer.parseInt(s2);
if(j <= 0)
hashtable.remove("port");
}
catch(Exception _ex)
{
hashtable.remove("port");
}
if((s2 = (String)hashtable.get("domain")) != null && s2.length() == 0)
hashtable.remove("domain");
if((s2 = (String)hashtable.get("reply")) != null && s2.length() == 0)
hashtable.remove("reply");
if((s2 = (String)hashtable.get("from")) != null && s2.length() == 0)
hashtable.remove("from");
if((s2 = (String)hashtable.get("to")) != null && s2.length() == 0)
hashtable.remove("to");
if((s2 = (String)hashtable.get("name")) != null && s2.length() == 0)
hashtable.remove("name");
if((s2 = (String)hashtable.get("dir")) != null && s2.length() == 0)
hashtable.remove("dir");
if(hashtable.get("port") == null)
hashtable.put("port", "25");
if(hashtable.get("subject") == null)
hashtable.put("subject", "see attachment for the uploaded file");
if(hashtable.get("attach") == null)
hashtable.put("attach", "1");
if(hashtable.get("dir") == null)
hashtable.put("dir", ".");
if(hashtable.get("edited") == null)
hashtable.put("edited", "");
}
%>
<%! private String readLine(byte abyte0[], int ai[], ServletInputStream servletinputstream, String s)
{
try
{
ai[0] = servletinputstream.readLine(abyte0, 0, abyte0.length);
if(ai[0] == -1)
return null;
}
catch(IOException _ex)
{
return null;
}
try
{
if(s == null)
return new String(abyte0, 0, ai[0]);
else
return new String(abyte0, 0, ai[0], s);
}
catch(Exception _ex)
{
return null;
}
}
%>
<%! private String replace(String s, String s1, String s2)
{
int i = s.indexOf(s1);
if(i < 0)
return s;
StringBuffer stringbuffer = new StringBuffer("");
if(i > 0)
stringbuffer.append(s.substring(0, i));
stringbuffer.append(s2);
if(i + s1.length() >= s.length())
{
return stringbuffer.toString();
} else
{
stringbuffer.append(replace(s.substring(i + s1.length()), s1, s2));
return stringbuffer.toString();
}
}
%>

<%
String user=(String)session.getValue("emp_id");
if(user == null)
{
response.sendRedirect("Redirect.html");
}
else
{
System.out.println("Starting NewEmployeeUploadSubmit.jsp");
String empid=(String)session.getValue("empidnew");
boolean flag=false;
String s = "";
String s3 = "";
String s4 = "";
String s5 = null;
String s6 = null;
String s7 = null;
ServletInputStream servletinputstream = null;
String s1 = request.getQueryString();
System.out.println("QueryString="+s1);
Hashtable hashtable = getConfig(s1);
s3 = (String)hashtable.get("dir");
System.out.println("s3="+s3);
s4 = (String)hashtable.get("reply");
s = (String)hashtable.get("name");
System.out.println("s="+s);
s5 = (String)hashtable.get("session");
servletinputstream = request.getInputStream();
s6 = request.getCharacterEncoding();
System.out.println("s6="+s6);
s7 = request.getContentType();
System.out.println("s7="+s7);
int i;
if((i = s7.indexOf("boundary=")) != -1)
{
s7 = s7.substring(i + 9);
s7 = "--" + s7;
}
String t7 = "";
try
{
// s1 = UploadFile(s, s3, s7, servletinputstream, s6);

Object forLock1 = new Object();
String newline = "\n";
String t6 = null;

byte abyte0[] = new byte[4096];
byte abyte1[] = new byte[4096];
int ai[] = new int[1];
int ai1[] = new int[1];
long l = 0L;
String t8 = getId();
String t4;
while((t4 = readLine(abyte0, ai, servletinputstream, s6)) != null)
{
int k = t4.indexOf("filename=");
if(k >= 0)
{
t4 = t4.substring(k + 10);
k = t4.indexOf("\"");
if(k > 0)
t4 = t4.substring(0, k);
break;
}
}
if(s != null)
t4 = s;
t7 = t4;
if(t7 != null)
{

t7 = getFileName(t7);
int index = t7.lastIndexOf(".");
String extension=t7.substring(index+1,t7.length());
if(!(t7.substring(0,index).equals(empid)))
{
%>
<%="<script Language='JavaScript'>alert('Please upload file with the name same as employee code.');history.back(); </script>"%>

<% return;
}
if(!extension.equals("jpg") && !extension.equals("jpeg"))
{
%>
<%="<script Language='JavaScript'>alert('Please upload files with extension jpg or jpeg only.');history.back(); </script>"%>

<% return;
}
String path = "/photos";
File f = new File(path);
if(f.exists())
{

String files[] = f.list();
for(int m=0;m<files.length;m++)
{
if(files[m].equals(t7))
{
flag =true;
%>
<%="<script Language='JavaScript'>alert('This filename already exists.Please give another file name');history.back(); </script>"%>
<%

break;
}
}
}
else
{
System.out.println("path does not exist");
}


String t5 = readLine(abyte0, ai, servletinputstream, s6);
if(t5.indexOf("Content-Type") >= 0)
readLine(abyte0, ai, servletinputstream, s6);
File file = new File(s3, t8);
FileOutputStream fileoutputstream = new FileOutputStream(file);
while((t5 = readLine(abyte0, ai, servletinputstream, s6)) != null)
{
if(t5.indexOf(s7) == 0 && abyte0[0] == 45)
break;
if(t6 != null && l <= 75L)
{
fileoutputstream.write(abyte1, 0, ai1[0]);
fileoutputstream.flush();
}
t6 = readLine(abyte1, ai1, servletinputstream, s6);
if(t6 == null || t6.indexOf(s7) == 0 && abyte1[0] == 45)
break;
fileoutputstream.write(abyte0, 0, ai[0]);
fileoutputstream.flush();
}
byte byte0;
if(newline.length() == 1)
byte0 = 2;
else
byte0 = 1;
if(t6 != null && abyte1[0] != 45 && ai1[0] > newline.length() * byte0)
fileoutputstream.write(abyte1, 0, ai1[0] - newline.length() * byte0);
if(t5 != null && abyte0[0] != 45 && ai[0] > newline.length() * byte0)
fileoutputstream.write(abyte0, 0, ai[0] - newline.length() * byte0);
fileoutputstream.flush();
fileoutputstream.close();
try
{
synchronized(forLock1)
{
File file1 = new File(s3, t7);
try
{
file1.delete();
}
catch(Exception _ex) { }
file.renameTo(file1);
}
}
catch(Exception _ex) { }
} else
{
throw new IOException();
}
//System.out.println("....t7="+t7);
}
catch(Exception _ex)
{
response.setContentType("text/html"); %>

<br><br>Could not upload file
<%
return;
}
String s2;
//if((s2 = (String)hashtable.get("log")) != null)
// writeLog(s2, request.getRemoteAddr(), s1);
if(s5 != null)
{

}
//System.out.println("S4="+s4);
if(s4 != null)
{
s4 = replace(s4, "$f", URLEncoder.encode(s1));
if(s4.toUpperCase().startsWith("HTTP"))
{
response.sendRedirect(response.encodeRedirectURL(s4));
} else
{
RequestDispatcher requestdispatcher = getServletConfig().getServletContext().getRequestDispatcher(s4);
requestdispatcher.forward(request,response);
}
} else
{
// response.sendRedirect("Thanks.html");

}

if(flag==false)
{
// String dept = request.getParameter("dept");
// String qry = "INSERT INTO newemployee(emp_id,state,empname,dept,desig,doj,details,showdate) VALUES('"+empid+"','"+state+"','"+empname+"',"+dept+",'"+desig+"','"+doj+"','"+details+"','"+date1+"')";
//System.out.println("qry="+qry);
//int n = db.insert(qry);
//System.out.println("n="+n);
int n=1;
if(n>0)
{
%>
<%="<script language='JavaScript'>alert('The new Employee is added'); location.href='Org_Depts_Links1.jsp';</script>"%>
<%
}

}
}
%>
 
Ranch Hand
Posts: 1847
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Rethink your design. Ideally you should have NO Java code at all in a JSP. In practice you should limit it to the absolute minimum possible.
 
Sheriff
Posts: 13411
Firefox Browser VI Editor Redhat
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sanny kumar,

Javaranch Tip:
If you are going to post more than a line or two of your code, wrap that
code in a set of UBB Code tags.
Doing so will help to preserve your code's indenting, making it easier to read.
If it is easier to read, more people will actaully read it and you will
stand a better chance of getting help with your question.
 
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Use commons-fileupload utility from apache for uploading files.

Sample Code:

fileUploadForm.jsp



GetFile.jsp:



This was done by using commons-fileupload 1.0. You can get the jars from http://jakarta.apache.org/commons/fileupload/
[ June 16, 2006: Message edited by: Balasubramani Dharmalingam ]
 
Sonu Philip
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Sanny and Balu!!
Thanks a lot for sending me the code itself.. Sanny's code is too large. So better i change to Balu's code.
Balu one doubt in that program you have used a package there.
1)What is the content of the package. and another doubt is it storing in the folder which u have specified there..
2)At the time of uploadig is that possible to store the filename and also the path of the file in the server in the oracle database.
3)When i try to retrieve the profile.. can i see the details of the particular person with his image...!!

Please reply ..
Once again thanks..

regards
Sonu
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic