How to convert Part to Blob, so I can store it in MySQL?

前端 未结 1 1458
清歌不尽
清歌不尽 2020-12-06 04:06

How to convert Part to Blob, so I can store it in MySQL? It is an image. Thank you

My form



        
相关标签:
1条回答
  • 2020-12-06 04:17

    The SQL database BLOB type is in Java represented as byte[]. This is in JPA further to be annotated as @Lob. So, your model basically need to look like this:

    @Entity
    public class SomeEntity {
    
        @Lob
        private byte[] image;
    
        // ...
    }
    

    As to dealing with Part, you thus basically need to read its InputStream into a byte[]. Apache Commons IO IOUtils is helpful here:

    InputStream input = uploadedFile.getInputStream();
    byte[] image = IOUtils.toByteArray(input); // Apache commons IO.
    someEntity.setImage(image);
    // ...
    

    Or if you prefer standard Java API which is only a bit more verbose:

    InputStream input = uploadedFile.getInputStream();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buffer = new byte[10240];
    for (int length = 0; (length = input.read(buffer)) > 0;) output.write(buffer, 0, length);
    someEntity.setImage(output.toByteArray());
    // ...
    
    0 讨论(0)
提交回复
热议问题