2013-03-27 106 views
0

我將圖片插入到Mysql數據庫中,圖片將被保存。如何使用spring從Mysql數據庫中檢索圖像?

File file = new File("G:/photos/New Folder (2)/www.geocities.com_cliknenjoy_lakshmimittal.jpg"); 

byte[] bFile = new byte[(int) file.length()]; 

try { 

    FileInputStream fileInputStream = new FileInputStream(file); 
    fileInputStream.read(bFile); 
    fileInputStream.close(); 
} catch (Exception e) { 
    e.printStackTrace(); 

} 
inpatient.setImagefile(bFile); 

我在mysql中使用blob數據類型。

private byte[] imagefile; 

public byte[] getImagefile() {  
    return imagefile; 
} 

public void setImagefile(byte[] imagefile) { 
    this.imagefile = imagefile;  
} 

現在我無法從mysqldatabase打開圖像文件,我該如何打開這一個?

+0

你是說你在使用Blob,但在你的例子中我可以看到byte []? – 2013-03-27 09:39:07

+0

您尚未展示如何存儲它或如何閱讀它。 – 2013-03-27 14:16:07

+0

雅我存儲的字節[],但我會存儲blob數據類型使用在MySQL中,我可以打開,看到從MySQL的圖像。但我需要通過編碼打開,圖像顯示從數據庫。我怎樣做? – 2013-03-28 08:17:46

回答

0

如果使用JPA註解,你可以註釋你的財產@Lob

@Lob 
private byte[] imagefile; 

也許還與@Basic(fetch=FetchType.LAZY),以避免數據的開銷。

斯特凡諾

- 編輯

一旦你堅持的圖像二進制內容作爲一個byte [],你有兩種方式來顯示圖像:寫一個新的servlet或一個新的控制器。首先增加了不必要的複雜性,所以我通常使用第二種方法。

首先你必須選擇控制器響應的路徑;假設"/dbresources/images/{id}"

的控制器會像

@Controller 
@RequestMapping(value = "/dbresources/images") 
public class PictureImageController { 

    @Autowired 
    private PictureService pictureService; // a service to retrieve pictures fomr DB 

    // getters and setters 

@RequestMapping(value = "/{id}") 
public void writePicture(@PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) throws IOException { 
     try{ 
      Picture img = pictureService.findById(id); 
      response.setContent(picture.getImagefile()); 
      response.setContentLength(picture.getImagefile().length); 

      //additionally, you should add the mime-type and the last 
      //change date (to allow the browsers to use the cache) if these info are available 

      response.getOutputStream().write(picture.getImagefile()); 
      response.setStatus(HttpServletResponse.SC_OK); 
     } 
     catch(Exception e){ 
      response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 404. Add specific catch for specific errors 
     } 
} 

然後在你的JSP(X),你需要編寫

<img src="/dbresources/images/[the id of the image to show]" /> 

控制器將攔截這個請求,並會對其進行處理在輸出流中寫入圖像的二進制內容。

希望這已經夠清楚了。不要相信代碼的正確性,因爲我在飛行中寫了它。

Stefano

+0

**我使用這個註釋,但我仍然得到該圖像將顯示[B @ 100271a像這樣,我如何打開文件?「」 – 2013-03-28 08:14:06

+0

我不明白你在尋找什麼。你的意思是,「我怎樣才能從應用程序的GUI中以二進制表示的形式顯示實際的圖像?」。如果是這樣,它是一個Web應用程序? – 2013-03-28 13:25:07

+0

**亞當然,我想改變轉換,如果有什麼可能在web應用程序中顯示gui模式?** – 2013-04-01 08:12:45

相關問題