Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save doc, pdf, and image files to mysql database using java?

Tags:

java

hibernate

I am trying to save .doc, .pdf, .txt, and image files into my database using hibernate, jsf, and mysql.

I have created a column to save the file of type BLOB. If I am saving .txt type then files are saved correctly.

If i am trying to save file of any other format then i am getting an exception. In my bean I have created a field name: byte[] file;

How i can save it correctly without any exceptions? Do I need to change datatype for mysql column or use a different field for java class?


(in response to BalusC)

This is the code which I am using for file writing. I am using fileInputStream and then saving the file using hibernate framework.

Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();

if (item.isFormField()) {
   String name = item.getFieldName();
   String value = item.getString();
} else {
   String fieldName = item.getFieldName();
   String fileName = item.getName();
   String contentType = item.getContentType();
   boolean isInMemory = item.isInMemory();
   long sizeInBytes = item.getSize();
   byte[] fileInBytes=item.get();


   try {
      File uploadedFile = new File("/home/db/webApp", fileName);
      uploadedFile.createNewFile();
      FileInputStream fileInputStream = new FileInputStream(uploadedFile);
      //convert file into array of bytes
      fileInputStream.read(fileInBytes);
      fileInputStream.close();
  } catch (Exception e) {
      e.printStackTrace();
  }

   UploadedFile object= new UploadedFile(); 
   object.setFile(fileInBytes);
   uploadedObject.setFileName(fileName);
   session.save(object);

UploadedFile is jsf managed bean:

public class UploadedFile{
   private String fileName;
   private byte[] file;
   /**
    * @return the fileName
    */
   public String getFileName() {
      return fileName;
   }
   /**
    * @param fileName the fileName to set
    */
   public void setFileName(String fileName) {   
      this.fileName = fileName;
   }
   /**
    * @return the file
    */
  public byte[] getFile() {
     return file;
  }
  /**
   * @param file the file to set
   */
  public void setFile(byte[] file) {
      this.file = file;
   }
}

and my database table has following structure:

Create UploadFile(FILE_NAME` VARCHAR(1000) NOT NULL,
 `FILE` BLOB NOT NULL);
like image 781
prt Avatar asked Nov 06 '22 04:11

prt


2 Answers

Your problem looks like it's a data type issue. A BLOB in MySQL is not very big. Try setting your table's column data type to a LONGBLOB instead.

like image 123
CaMiX Avatar answered Nov 09 '22 12:11

CaMiX


Its better to save the file in a location and save the location in the database

like image 30
Abi Avatar answered Nov 09 '22 11:11

Abi