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);
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.
Its better to save the file in a location and save the location in the database
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With