5

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);
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
prt
  • 51
  • 1
  • 1
  • 2

4 Answers4

2

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.

CaMiX
  • 680
  • 1
  • 7
  • 17
1

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

Abi
  • 4,718
  • 4
  • 20
  • 29
  • 2
    In some very trivial cases perhaps, but generally suggesting to store binary data on the file system instead of in a database is not a very good idea. – jarnbjo Jan 10 '11 at 12:58
  • @jarnbjo It depends. Imagine you have a social network and need to store millions of images. Would you store all this data in a database ? – James P. Aug 26 '12 at 19:59
  • @jarnbjo That's a debate in itself. See this question for pros and cons. http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay – James P. Aug 27 '12 at 13:18
  • 6
    @James: So why did you ask? Did you expect me to come to a conclusive and well argumented answer in a 600 character comment? – jarnbjo Aug 27 '12 at 13:43
  • @Abi how to save file in a location in java ? – Rahul Kulhari Aug 27 '13 at 04:20
0

Store the file meta info such as location in db, but synchronize db and file system will be an issue.

卢声远 Shengyuan Lu
  • 31,208
  • 22
  • 85
  • 130
-1
package com.server;


import java.io.*;

import java.sql.*;
import java.util.*;
import java.text.*;
import java.util.regex.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import org.mortbay.jetty.Response;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;   
import java.sql.*;   
import javax.servlet.http.HttpServlet;   
import javax.servlet.http.HttpServletRequest;   
import javax.servlet.http.HttpServletResponse;   
import javax.servlet.ServletInputStream.*;   
import java.io.PrintWriter;   

public class XmlServlet extends HttpServlet {   

public void doPost(HttpServletRequest req,HttpServletResponse res)   
{ 
    File uploadedFile;


    System.out.print("on server");
try{   

Class.forName("com.mysql.jdbc.Driver");   
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3308/image","root","root1");  

PrintWriter out=res.getWriter();   

//out.println("<br>Content type is :: " +contentType);   
//to get the content type information from JSP Request Header   
String contentType = req.getContentType();   
int flag=0;   
FileInputStream fis=null;   
FileOutputStream fileOut=null;   
//here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0   
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))   
{   
DataInputStream in = new DataInputStream(req.getInputStream());   
//we are taking the length of Content type data   
int formDataLength = req.getContentLength();   
byte dataBytes[] = new byte[formDataLength];   
int byteRead = 0;   
int totalBytesRead = 0;   

//this loop converting the uploaded file into byte code   
while (totalBytesRead < formDataLength) {   
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);   
totalBytesRead += byteRead;   
}   

String file = new String(dataBytes);   
//for saving the file name   
String saveFile = file.substring(file.indexOf("filename=\"") + 10);   
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));   
out.println("savefiledddd"+saveFile);   
int extension_save=saveFile.lastIndexOf("\"");   
String extension_saveName=saveFile.substring(extension_save);   

//Here we are invoking the absolute path out of the encrypted data   

saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));   
int lastIndex = contentType.lastIndexOf("=");   
String boundary = contentType.substring(lastIndex + 1,contentType.length());   
int pos;   

//extracting the index of file   
pos = file.indexOf("filename=\"");   
pos = file.indexOf("\n", pos) + 1;   
pos = file.indexOf("\n", pos) + 1;   
pos = file.indexOf("\n", pos) + 1;   
int boundaryLocation = file.indexOf(boundary, pos) - 4;   
int startPos = ((file.substring(0, pos)).getBytes()).length;   
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;   

out.println("savefile"+saveFile);   

int file_No=22;  

 uploadedFile=new File("./war/img");

    uploadedFile.mkdir();


  String kk=uploadedFile.getAbsolutePath();


  String pathname_dir=kk+"/"+saveFile;   
   //String pathname_dir="C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\jk\\"+saveFile;   
    File filepath=new File(pathname_dir);   
     out.println("filepath_  "+filepath);   
    fileOut = new FileOutputStream(filepath);   
    fileOut.write(dataBytes, startPos, (endPos - startPos));   
    fileOut.flush();   
    out.println("<h1> your files are saved</h1></body></html>");   
     out.close();   

        File database_filename=new File(pathname_dir);   
            fis=new FileInputStream(database_filename);   

int len=(int)database_filename.length();
            PreparedStatement ps = conn.prepareStatement("insert into new (image) values (?)");   
            ps.setBinaryStream(1,fis,len);   
            ps.executeUpdate();   
            ps.close();   
            flag=1;   

}   

if(flag==1)   
{   
fileOut.close();   
fis.close();   
}   
}catch(Exception e)   
{   
System.out.println("Exception Due to"+e);   
e.printStackTrace();   
}   
}   
}   

It's a server code. By that code you can upload any file which is stored in database and store that file on server side at (img) folder. By using the reference of that you can access the file.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
monica bubna
  • 616
  • 5
  • 12