i need help..to anyone who expert in servlet & Jsp..
my problem is..i do not know how to upload image via html/jsp..
>before that i already ask mr.google but.. i got sux answer.

so, this code work's and upload succesfully but it must manually put the destination file type string in this class >> File file = new File("C:/images/5.jpg");

import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class InsertImage extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost:3306/test";
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(connectionURL, "root", "");
PreparedStatement ps = con.prepareStatement("INSERT INTO pictures VALUES(?,?)");
File file = new File("C:/images/5.jpg");
FileInputStream fs = new FileInputStream(file);
ps.setInt(1,1);
ps.setBinaryStream(2,fs,fs.available());
int i = ps.executeUpdate();
if(i!=0){
pw.println("image inserted successfully");
}else{
pw.println("problem in image insertion");
}
} catch (Exception e){
System.out.println(e);
}
}
}

then, when i try insert image using html/jsp form, it failed to insert that image into database.. and i got blank white screen.

here the html form..

<html>

<head><title>Image Upload</title></head>

<body>
	<form action="UploadImage.do" method="post" enctype="multipart/form-data" name="productForm" id="productForm"><br><br>
		<table width="400px" align="center" border=0 style="background-color:ffeeff;">
			<tr>
				<td align="center" colspan=2 style="font-weight:bold;font-size:20pt;">Image Details</td>
			</tr>

			<tr>
				<td align="center" colspan=2>&nbsp;</td>
			</tr>

			<tr>
				<td>Image Link: </td>
				<td>
					<input type="file" name="file" id="file">
				<td>
			</tr>

			<tr>
				<td></td>
				<td><input type="submit" name="Submit" value="Submit"></td>
			</tr>
			<tr>
				<td colspan="2">&nbsp;</td>
			</tr>

		</table>
	</form>
</body>

</html>

and this is my xml.web

<servlet>
<servlet-name>InsertImage</servlet-name>
<servlet-class>InsertImage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InsertImage</servlet-name>
<url-pattern>/UploadImage.do</url-pattern>
</servlet-mapping>

and this is mysql database.. field

CREATE TABLE `picture` (
`id` int(10) NOT NULL auto_increment,
`image` blob,
PRIMARY KEY (`id`)
)

hope this info can help..thanks

Dani AI

Generated

A few things are biting you here. First, your form posts with multipart/form-data, but your servlet only implements doGet. The container will call doPost, so you never reach the code that writes to the DB, which explains the blank page. Second, a multipart request is not available via normal request streams/parameters; you must parse the uploaded part. Third, as noted, your SQL targets a table named "pictures" while you created "picture"; also, since id is AUTO_INCREMENT, do not insert it explicitly. Finally, as hinted, pick a BLOB size that matches your files (BLOB is ~64KB; MEDIUMBLOB ~16MB; LONGBLOB ~4GB).

Minimal servlet-side example using Servlet 3.x upload handling:

// Map this servlet in web.xml to /UploadImage.do
@MultipartConfig(maxFileSize = 5 * 1024 * 1024) // 5 MB
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    Part filePart = req.getPart("file"); // matches <input name="file">
    if (filePart == null || filePart.getSize() == 0) {
        resp.sendError(400, "No file uploaded");
        return;
    }
    try (InputStream in = filePart.getInputStream();
         Connection con = /* get a JDBC connection */;
         PreparedStatement ps =
             con.prepareStatement("INSERT INTO picture(image) VALUES (?)")) {
        ps.setBinaryStream(1, in, filePart.getSize()); // or ps.setBlob(1, in)
        ps.executeUpdate();
        resp.getWriter().println("image inserted successfully");
    } catch (Exception e) {
        resp.sendError(500, e.toString());
    }
}

Practical checks:

  • Keep your web.xml mapping and form action aligned: /UploadImage.do.
  • Avoid InputStream.available() for length; use part.getSize().
  • Specify column names in INSERT to avoid order issues.
  • If uploads are large, increase MySQL max_allowed_packet and choose MEDIUMBLOB/LONGBLOB.
  • For older containers (pre-Servlet 3.0), use a multipart library to parse the file part before inserting.

Recommended Answers

All 6 Replies

Read this reply

thanks peter.. it help a bit.. otherwise i'm still beginner to follow that particular method and of coz i need big time to understand all of that code function properly/perfectly..
but i need emergencies help to experties to modify my code above.. and my gol only insert image to mysql database via html/jsp form..
tq..

tu codigo esta bien ... el error es ...PreparedStatement ps = con.prepareStatement("INSERT INTO pictures VALUES(?,?)"); <--- "pictures" es "picture"

commented: Not using English and then posting email address, bad! -2

ivanslayer, please post in English on the forums.

Instead of blob use "longblob" data type for attribute image in picture table...

Mounika, I think it's safe to say that after 3 years, either they found the sollution, or are no longer looking anyway.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.