如何使用java将doc,pdf和image文件保存到mysql数据库? [英] How to save doc, pdf, and image files to mysql database using java?
问题描述
我正在尝试保存 .doc
, .pdf
, .txt
,并使用hibernate,jsf和mysql将图像文件存入我的数据库。
I am trying to save .doc
, .pdf
, .txt
, and image files into my database using hibernate, jsf, and mysql.
我创建了一个列来保存BLOB类型的文件。如果我保存 .txt
类型,则文件保存正确。
I have created a column to save the file of type BLOB. If I am saving .txt
type then files are saved correctly.
如果我正在尝试保存任何文件其他格式然后我得到一个例外。
在我的bean中,我创建了一个字段名: byte [] file;
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;
我怎么能没有任何例外,保存正确吗?我是否需要更改mysql列的数据类型或为java类使用不同的字段?
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?
(响应BalusC)
(in response to BalusC)
这是我用于文件编写的代码。我正在使用 fileInputStream
,然后使用hibernate框架保存文件。
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
是jsf托管bean:
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);
推荐答案
最好将文件保存在$ b的位置$ b并保存数据库中的位置
Its better to save the file in a location and save the location in the database
这篇关于如何使用java将doc,pdf和image文件保存到mysql数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!