galao
galao

Reputation: 1301

inserting an image in the database with a BLOB datatype

entity:

@Lob
@Column(name = "logo")
private byte[] logo;

form:

<h:form enctype="multipart/form-data">  
    <p:messages showDetail="true"/>  

    <p:fileUpload value="#{testController.file}" 
                  update="messages"  
                  mode="simple"
                  sizeLimit="1048576"   
                  allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>  

    <p:growl id="messages" showDetail="true"/>  

    <p:commandButton value="Submit" ajax="false"  
                     actionListener="#{testController.upload}"/>  
</h:form>  

bean:

private testEntity current;
private UploadedFile file;

public UploadedFile getFile() {
    return file;
}

public void upload() {
    if (file != null) {
        try {
            byte[] data = file.getContents();
            current.setLogo(data);

            getFacade().edit(current);
            JsfUtil.addSuccessMessage("Successful! " + file.getFileName() + " is uploaded.");
        } catch (Exception e) {
        }
    }
}

when i try to upload files like 80kb picture, it will give me this exception

Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'logo' at row 1

but if i upload a mere < 10kb pictures, the code works.

using JSF 2.0, Primefaces 3.5, most codes are auto generated using CRUD.

Upvotes: 1

Views: 4386

Answers (1)

Ares
Ares

Reputation: 5903

The problem is that your database column is set to stored less than what you are trying to store. That's what truncating means.

You will need to change your database column definition to LONGBLOB.

Upvotes: 1

Related Questions