|
Image upload from JSP to Data Base step by step :
step 1 :
In the JSP
<form name="regform2" method="post" enctype="multipart/form-data">
<input type="file" name="ImageFile" id="ImageFile" onChange="uploadImage()"/>
</form>
java script :
function uploadImage(){
document.regform.action ="<%=request.getContextPath()%>/dfdmin?cmd=uploadimage";
document.regform.submit();
}
Step 2.
In the servlet - add the below code.
This will upload your image to server (D:\\) or In unix you can mention /home/user like that
String rtempfile = File.createTempFile("temp","1").getParent();
MultipartRequest multi = new MultipartRequest(request, rtempfile, 500000 * 1024);
File rnewfile=null;
rnewfile = new File("D:\\"+"jsp"+File.separator+"images"+File.sep arator+"uploadImage"+File.separator);
if(rnewfile.exists()){
}else{
rnewfile.mkdirs();
}
File f = multi.getFile("ImageFile");
System.out.println(f.getName());
FileInputStream fin =new FileInputStream(f);
RandomAccessFile r = new RandomAccessFile(rnewfile+File.separator+f.getName (),"rw");
filename = f.getName();
// FileOutputStream fos =new FileOutputStream(rnewfile);
byte sizefile[] = new byte[5000000];
fin.read(sizefile);
// fos.write(sizefile);
r.write(sizefile);
//fos.close();
r.close();
fin.close();
DAO.upload(f); // Call to DAO for insert image into database.
goto techfaq360.com/jsp_interview_questions.jsp?qid=348 for details
|