0% found this document useful (0 votes)
109 views

JSP For Uploading The Image

The JSP code handles uploading an image file to the server by parsing the multipart form data submitted from an HTML form, extracting the file data and metadata, and saving the file to the server. It also provides some example functions for selecting an image from the database, getting it as a byte array or BufferedImage, and inserting image data into the database.

Uploaded by

Sai Vellanki
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views

JSP For Uploading The Image

The JSP code handles uploading an image file to the server by parsing the multipart form data submitted from an HTML form, extracting the file data and metadata, and saving the file to the server. It also provides some example functions for selecting an image from the database, getting it as a byte array or BufferedImage, and inserting image data into the database.

Uploaded by

Sai Vellanki
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

JSP for Uploading the image

<form name="uploadForm" action="upload.jsp" enctype="multipart/form-data"


method="post">
<input type="file" name="file"/>
<input TYPE=Button name='Upload' Value='Upload'
onClick="uploadForm.Upload.value='Uploading...';document.uploadForm.action='up
load.jsp';document.uploadForm.submit()">
</form>
}

.jsp

<%

response.setContentType("text/html");
response.setHeader("Cache-control","no-cache");

String err = "";

String lastFileName = "";

String contentType = request.getContentType();


String boundary = "";
final int BOUNDARY_WORD_SIZE = "boundary=".length();
if(contentType == null || !contentType.startsWith("multipart/form-data"))
{
err = "Ilegal ENCTYPE : must be multipart/form-data\n";
err += "ENCTYPE set = " + contentType;
}else{
boundary = contentType.substring(contentType.indexOf("boundary=") +
BOUNDARY_WORD_SIZE);
boundary = "--" + boundary;
try {
javax.servlet.ServletInputStream sis = request.getInputStream();
byte[] b = new byte[1024];
int x=0;
int state=0;
String name=null,fileName=null,contentType2=null;
java.io.FileOutputStream buffer = null;
while((x=sis.readLine(b,0,1024))>-1) {
String s = new String(b,0,x);
if(s.startsWith(boundary)) {
state = 0;
//out.println("name="+name+"<br>");
//out.println(fileName+"<br>");

name = null;
contentType2 = null;
fileName = null;

}else if(s.startsWith("Content-Disposition") && state==0) {


state = 1;
if(s.indexOf("filename=") == -1)
name = s.substring(s.indexOf("name=") +
"name=".length(),s.length()-2);
else {
name = s.substring(s.indexOf("name=") +
"name=".length(),s.lastIndexOf(";"));
fileName = s.substring(s.indexOf("filename=") +
"filename=".length(),s.length()-2);
if(fileName.equals("\"\"")) {
fileName = null;
}else {
String userAgent = request.getHeader("User-Agent");
String userSeparator="/"; // default
if (userAgent.indexOf("Windows")!=-1)
userSeparator="\\";
if (userAgent.indexOf("Linux")!=-1)
userSeparator="/";
fileName =
fileName.substring(fileName.lastIndexOf(userSeparator)+1,fileName.length()-1);
if(fileName.startsWith( "\""))
fileName = fileName.substring( 1);
}
}
name = name.substring(1,name.length()-1);
if (name.equals("file")) {
if (buffer!=null)
buffer.close();
lastFileName = fileName;
buffer = new java.io.FileOutputStream("/Program Files/Apache
Group/Tomcat 4.1/webapps/jspcart/images/"+fileName);
}
}else if(s.startsWith("Content-Type") && state==1) {
state = 2;
contentType2 = s.substring(s.indexOf(":")+2,s.length()-2);
}else if(s.equals("\r\n") && state != 3) {
state = 3;
}else {
if (name.equals("file"))
buffer.write(b,0,x);
}
}
sis.close();
buffer.close();
}catch(java.io.IOException e) {
err = e.toString();
}
}
boolean ok = err.equals("");
if(!ok) {
out.println(err);
}else{
%>
<SCRIPT language="javascript">
history.back(1)
alert('Uploaded <%=lastFileName%>');
window.location.reload(false)
</SCRIPT>
<%
}
out.println("done");
%>

Please refer the following code may be useful

The function selectImage can be used to get the Image and then disply.

While displaying the Image please set the content type “image/pjpeg”

public int insertImage(Image image) throws SQLException {


Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection conn =
DriverManager.getConnection("jdbc:mysql://"+"db_address");
int id = -1;
String sql = "insert into test (img) values (?)\n";
PreparedStatement ps = this.getStatement(sql); // this method is
trivial
byte [] bytes = this.getBytes(image); // * see below
ps.setBytes(1, bytes);
ps.executeUpdate();
id = ps.getGeneratedKeys().getInt(0); //Actually I couldn't make this
line work yet.
return id;
}

public Image selectImage(int id) throws SQLException {


Image img = null;
String sql = "select img from test where id = ?\n";
PreparedStatement ps = getStatement(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
byte [] bytes = rs.getBytes(1);
img = this.getImage(bytes); // * see below
}
return img;
}
public byte [] getBytes(Image image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(this.getBufferedImage(image), "JPEG", baos);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return baos.toByteArray();
}
public Image getImage(byte [] bytes) {
Image image = null;
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
try {
image = ImageIO.read(bais);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
return image;
}

public BufferedImage getBufferedImage(Image image) {


int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
g2d.drawImage(image, 0, 0, null);
return bi;
}

You might also like