2011-01-10 94 views
5

我試圖使用hibernate,jsf和mysql將.doc,.pdf,.txt和圖像文件保存到我的數據庫中。如何使用java將doc,pdf和圖像文件保存到mysql數據庫?

我已經創建了一個列來保存BLOB類型的文件。如果我正在保存.txt類型,則會正確保存文件。

如果我想保存任何其他格式的文件,那麼我得到一個異常。 在我的豆中,我創建了一個字段名稱:byte[] file;

我如何正確保存而沒有任何異常?我是否需要爲mysql列更改數據類型或爲java類使用不同的字段?


(響應BalusC)

這是我使用的文件寫入的代碼。我正在使用fileInputStream,然後使用hibernate框架保存文件。

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:

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; 
    } 
} 

和我的數據庫表有以下結構:

Create UploadFile(FILE_NAME` VARCHAR(1000) NOT NULL, 
`FILE` BLOB NOT NULL); 
+0

你會得到什麼異常? – soulcheck 2011-11-04 08:50:54

回答

3

其更好地將文件保存在一個位置 和保存位置數據庫

+0

也許在一些非常微不足道的情況下,但通常建議將二進制數據存儲在文件系統而不是數據庫中並不是一個好主意。 – jarnbjo 2011-01-10 12:58:24

+0

@jarnbjo這取決於。想象一下你有一個社交網絡,需要存儲數以百萬計的圖片。你會將所有這些數據存儲在數據庫中嗎? – 2012-08-26 19:59:28

0

存儲文件meta i nfo如db中的位置,但同步db和文件系統將是一個問題。

2

您的問題看起來像是數據類型問題。 MySQL中的BLOB不是很大。嘗試將您的表的列數據類型設置爲LONGBLOB。

0
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(); 
} 
} 
} 

這是一個服務器代碼。通過該代碼,您可以上傳存儲在數據庫中的任何文件,並將該文件存儲在服務器端的(img)文件夾中。通過使用您可以訪問該文件的參考。

相關問題