1

This line of code:

document.setContent((Blob) file);

Is throwing this error:

org.springframework.web.multipart.commons.CommonsMultipartFile cannot be cast to java.sql.Blob

Where file is a MultipartFile.

Eclipse does not throw any warning message from the "offending" line of code above. In fact, eclipse added the (Blob) cast itself as part of a suggested fix.

Is there some other way that I can quickly and easily convert a MultipartFile to a Blob?

I have been working on this problem for a number of days now to no avail. See postings here and here. Simply being able to convert the MultipartFile to a Blob in a line or two of code would be an easy, elegant solution to an otherwise overcomplicated problem.

Community
  • 1
  • 1
CodeMed
  • 9,527
  • 70
  • 212
  • 364

1 Answers1

4

Take a look at docs and this question.
What I've come up with is to use byte[]:

byte[] contents = file.getBytes();
Blob blob = new SerialBlob(contents);
document.setContent(blob);
Community
  • 1
  • 1
Michał Rybak
  • 8,648
  • 3
  • 42
  • 54
  • Thank you. +1 for trying to help. System.out.println(document.getContent().length()); Shows the blob has a length when called after being set by your code. But the application is not inserting the blob into the database. I guess technically you answered my question, so I will mark this as answered, but will you please look at the other two postings I linked to in my original posting above? If you could help me get this working, I would be very grateful, and mark all three as answered when the application successfully inserts a document into the database. – CodeMed Dec 15 '13 at 03:42
  • I put a large bounty on a related question. Do you mind taking a look at it and submitting an answer? I will award the large bounty to the person who provides a working solution. Here is the link: http://stackoverflow.com/questions/20586865/document-not-saving-in-spring-jpa-document-manager-application – CodeMed Dec 17 '13 at 00:11
  • sorry but I'm not that much into Hibernate at the moment. I've read your other questions, but I'm afraid I can't help. I can only suggest using debugger to see precisely in which step the data is lost. Also consider enabling Hibernate logging to see what SQL it executes, if you haven't done this already. – Michał Rybak Dec 17 '13 at 00:27
  • Thank you for your suggestions. I am a self-taught programmer, and I do not know how to do the things you are suggesting. Are you willing to post links to instructions? – CodeMed Dec 17 '13 at 00:29
  • Read [here](http://www.mkyong.com/hibernate/hibernate-display-generated-sql-to-console-show_sql-format_sql-and-use_sql_comments/) about enabling Hibernate showing SQL. As for the debugger, it depends on your version of Eclipse, but you can just google it and find some articles like [this one](http://www.vogella.com/articles/EclipseDebugging/article.html). Good luck! – Michał Rybak Dec 17 '13 at 00:34