2

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.

2 Answers2

2

In your code you write:

ps.setBlob(5, (Blob) InputStream);

According to javadoc for PreparedStatement this int, 5 is the parameter index. As the error is stating you only have 3 parameters.

You need to change this to 3? - looking at your SQL statement I think you may have forgotten you have copied and pasted from somewhere and haven't yet edited it.

Mark W
  • 5,824
  • 15
  • 59
  • 97
  • I haven't copy pasted the entire thing, rather taking some from my working register servlet, and then abit from looking through various sites. I put 5, because I thought I specified the number of the column in the row. I tried change it to 3, and same error. I'm sorry if my code seem obnoxious and cheap. – user3873428 Mar 02 '15 at 12:48
  • Does this statement match your database table architecture? "insert into user where email=? and name=? values(?)" – Mark W Mar 02 '15 at 15:13
  • no it does not! I also figured you can't insert into an existing row. And changed the prepared statement. Now I'm not getting any SQL errors. But not uploading anything to my table. I guess I'm doing something wrong with the file conversion. – user3873428 Mar 02 '15 at 16:02
0

These lines are the problem, you can't use Part object as Blob or InputStream. A cast exception should happen there.

Part filePart = req.getPart("photo");
Part InputStream = filePart; //this line is not needed at all
ps.setBlob(1, (Blob) InputStream);

Try something like this

ps.setBlob(1, filePart.getInputStream());

or

ps.setBinaryStream(1, filePart.getInputStream());
dimm
  • 1,792
  • 11
  • 15
  • Thanks for you answer. I tried both of the options, and getting: at java.lang.Thread.run(Unknown Source) java.lang.NullPointerException at com.event.changeImage.doPost(changeImage.java:51) – user3873428 Mar 02 '15 at 18:46
  • Getting the nullpointer exception at the line where: ps.setBlob(1, filePart.getInputStream()); is implemented. – user3873428 Mar 02 '15 at 20:19