• Post Reply Bookmark Topic Watch Topic
  • New Topic

Data (BLOB) Modifies After Insertion To MySql (Jsp, Servlet)  RSS feed

Eduard Tarassov
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My Problem. MySQL changes data I upload to db as a Blob file and then retrieve it back. So image does not want to appear on my jsp page.

My program uses jsp/servlet datasource connection to MySql.

Step 1. My problem occurs when I am trying to upload image using jsp and sending it to the doPost method by passing request to InputStream. Then I just reading inputStream into byte[]. And translating byte[] into java.sql.Blob type.

Step 2. After all these steps I am sending the MySql connection to my java class Model. Then I am transforming my byte[] b file to Blob file.

Step 3. And sending this data (and some more stuff) to the MySql database with PreparedStatement and storing it there as MEDIUMBLOB.

Furthermore, I am closing Connection and PreparedStatement.

Step 4. On another jsp page I am going to the doGet method in my servlet (with setting the connection to DB of course) and making the statement there to take image as Blob. And converting it to the byte[].

So, when I am looping through the byte[] b after Step 1 I am getting next data for my image:
-1-40-1-32016747073700120010100-1-37067086676587779981012201312111112251819152029263130292628283236463932344435282840554 ... (lots of numbers there)

And when I am doing the same at the end of Step 4 after converting Blob from MySQL to byte[]. I am getting next data:

My Chrome Console in Inspect Element shows next error:

Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH

I am not posting here some stuff like try/catch blocks and setting the connection. Don't want to obstruct you with dozens lines of code. I have already checked that data does not change while translations byte[] to Blob and otherwise in java code. So the problem is that MySQL modifies data somehow. Also want to mention that I am using the Tomcat server.

Would be great if someone helped me to understand the problem and how to solve it. (I don't want to store data as huge varchar or byte[].) Thanks.
Dave Tolls
Ranch Hand
Posts: 2504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Your problem is in here.
The read() method returns a count of the number of bytes read.
You need to use that when you write the byte array, so it only writes the bytes that have been read, and not the entire array, some of which at the end will be junk.

That should (assuming I haven't missed anything later on) cure your problem.
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!