mardi 3 mars 2015

Send image to mySQL with servlet, ajax, jquery



I'm having some trouble getting my image uploaded to my SQL through JDBC. mySQL table is user(email, pass, name, lastname, profilePicture), profilePicture is sat to blob.


Been stuck at this for some days now, and just can't let it go.


my form:



<form method="POST" id="changeImage2" enctype="multipart/form-data">
<input type="file" name="photo" /> <br>
<input type="button" value="Change Picture" id="changeImage1">
</form>


my servlet:



@MultipartConfig
public class changeImage extends HttpServlet{

/**
*
*/
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

resp.setContentType("text/html");
PrintWriter out = resp.getWriter();

Part filePart = req.getPart("photo");

Object email = req.getSession().getAttribute("email");
Object name = req.getSession().getAttribute("name");

try{

Class.forName("com.mysql.jdbc.Driver");

Connection myConn = DriverManager.getConnection("", "", "");

PreparedStatement ps = myConn.prepareStatement("update user set profilePicture=? where email=? and name=?");

ps.setBlob(1, filePart.getInputStream());
ps.setString(2, (String) email);
ps.setString(3, (String) name);
ps.executeUpdate();

} catch (Exception e){
e.printStackTrace();
}
}
}


my ajax/jquery:



<script>
$(document).ready(function() {
$('#changeImage1').click(function() {
var dataForm = $('#changeImage2').serialize();
$.ajax({
type : 'POST',
url : 'changeImage',
data : dataForm,
success : function(data) {
$('#gg1').text(data);
},
error : function() {
$('#gg1').text("Fail");
},
});
});
});
</script>


When running this I get the error:



SEVERE: Servlet.service() for servlet [changeImage] in context with path [/Event] threw exception [org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/form-data stream, content type header is null] with root cause org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/form-data stream, content type header is null





Aucun commentaire:

Enregistrer un commentaire