Trying to upload a file to my servlet without page refresh with ajax.
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
I tried use another form and do without the ajax/jquery:
<form action="changeImage" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Change Picture" />
</form>
With this it works. So I'm guessing the JDBC and Servlet is sat up properly. And that I'm not using Ajax/Jquery properly.