2013-08-18 35 views
0

我試圖將我的應用程序中每個員工的照片保存在他/她的配置文件旁邊,然後在任何用戶打開此員工配置文件時檢索此照片,因此我製作了以下類:保存 - 檢索圖像數據庫休眠

public class Employee { 
@Id 
@GeneratedValue(strategy=GenerationType.AUTO) 
@Column(name="EMPLOYEE_ID") 
private Long id; 
. 
//many other fields goes here... 
. 
@OneToOne(cascade={CascadeType.ALL}) 
@PrimaryKeyJoinColumn 
private EmployeePicture employeepicture;  
} 

public class EmployeePicture { 
@Id 
@GeneratedValue(strategy=GenerationType.AUTO) 
@Column(name="EMPPIC_ID") 
private Long id; 

@Column(name="EMPLOYEE_PIC") 
@Lob 
private Blob employeePicture; 
} 

然後,我創建除了我已經有EmployeeDAO類中的以下DAO類,當然...

@Repository 
public class EmployeePictureDAO implements IEmployeePictureDAO { 

@Autowired 
SessionFactory sessionfactory; 

public void saveEmployeePicture(EmployeePicture employeepicture) { 
sessionfactory.getCurrentSession().save(employeepicture); 
} 
public void updateEmployeePicture(EmployeePicture employeepicture) { 
sessionfactory.getCurrentSession().update(employeepicture); 
} 
public void deleteEmployeePicture(EmployeePicture employeepicture) { 
sessionfactory.getCurrentSession().delete(employeepicture); 
} 
public EmployeePicture getEmployeePictureByPK(Long id) {   
return (EmployeePicture)sessionfactory.getCurrentSession().get(EmployeePicture.class,id); 
} 
} 

隨着服務層類的,我只有的EmployeeService類我相信應該稱爲EmployeeDAO和EmployeePictureDAO方法,因爲數據和圖片將在同一時間保存/更新和刪除。但不幸的是,我找不到(在搜索網頁後)/如何從/向JSP保存/檢索圖像。那麼,有人可以通過給我一個關於如何在Service/Controller類和JSP中保存/檢索員工鏡像的示例代碼來幫助我嗎?

Thanksf或你的時間

回答

0

下面是如何顯示HTML圖像:當瀏覽器看到這個<img>標籤在HTML頁面

<img src="the-url-of-the-image" /> 

,它會發送另一個HTTP請求中引用的URL標籤和服務器發回一個包含圖像字節的響應,以及一個內容類型標題,告訴瀏覽器它是哪種圖像(image/jpg,image/png等)。

當圖像是一個靜態文件時,您通常沒有任何操作,因爲Web服務器會爲您執行所有操作:它從文件擴展名中推導內容類型,讀取文件並將其數據發送到響應。

就你而言,由於圖像在數據庫中,你必須自己做,通過編寫一個servlet或Spring MVC控制器,從數據庫獲取圖像,並將其發送回HTTP響應,使用適當的conent類型的頭文件集。

所以,對於員工個人資料頁面產生的視圖將包含類似

<img src="<c:url value='/employeePicture"> 
       <c:param name='employeeId' value='${employee.id}'/> 
      </c:url>" /> 

而且你必須映射到/employeePicture控制器,將從數據庫加載員工圖片,設置響應內容類型的頭部,併發回圖像的字節。

+0

非常感謝您的回覆,我在我的問題提到我非常堅持了建築規範對於將圖像保存到數據庫並將其重新加載以準備在中顯示的控制器。我在網上搜索了任何樣本,但找不到任何樣本,如果您可以請給我提供示例或甚至鏈接到一個很好的示例。謝謝 – MChan

+0

我向您解釋瞭如何顯示存儲在數據庫中的圖像。要上傳它,請閱讀Spring文檔:它有一個部分和一些示例,說明如何處理文件上傳:http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/htmlsingle/ #mvc-multipart –

0

我們有一點點不同的策略 - 我們只存儲圖片的路徑,但這種方法可以幫助你:

@ResponseBody 
@RequestMapping(value = "/images/{imageId}", method = RequestMethod.GET, produces="image/*") 
public void getImage(@PathVariable Long imageId, HttpServletResponse response) throws IOException { 
    response.setContentType("image/jpeg"); 
    ArticleImage requestedImage = articleImageService.findOne(imageId); 
    InputStream in = servletContext.getResourceAsStream(requestedImage.getPath()); // Make "in" object creation from Blob here (instead of loading resource as stream) 
    if (in != null) { 
     IOUtils.copy(in, response.getOutputStream()); 
    }else { 
     logger.error("Missing requested image " + requestedImage); 
    } 
} 

上觀看我們:

<img src="${home}/images/${article.id}" /> 

所以瀏覽器發出GET與URL請求「/ images/{id}」並渲染獲得的圖像。

希望它可以幫助

+0

User518469你能否給我提供示例代碼,甚至是一個鏈接到如何在Controller和Service類中'保存'圖像的在線示例?問題是我不知道如何讓用戶從他/她的驅動器中選擇圖像,然後將其上傳到我們的服務器,以保存爲Blob或作爲圖像路徑的URL。在此先感謝 – MChan

+0

首先使用正確的enctype製作表單:

。第二個 - 使用參數中的文件創建控制器方法:public String upload(@RequestParam MultipartFile imageFile,..)。第三 - 將圖像寫入文件或數據庫。使用imageFile.getBytes()方法從imageFile創建inputStream – yname

+0

您可以存儲圖像:1)在文件系統2)在數據庫3)使用特殊的雲服務(如dropbox或cloudinary)。使用哪種方法取決於您的情況和您的偏好 – yname

0

要上傳您可以使用Commons File Upload圖像。 Here是一個示例代碼(而不是保存到文件系統,您可以將它保存在數據庫中)。你可以在網上找到很多關於文件上傳的例子。

對於檢索,我建議使用專用於顯示圖像的servlet。下面是一個例子

@WebServlet("/image/*") 
public class ImageServlet extends HttpServlet { 

/** 
* 
*/ 
private static final long serialVersionUID = 1L; 

private static final int DEFAULT_BUFFER_SIZE = 10240; 

protected void doGet(HttpServletRequest request, 
     HttpServletResponse response) throws ServletException, IOException { 
    // Get requested image by path info. 
    String requestedImage = request.getParameter("value"); 
    // Check if file name is actually supplied to the request URI. 
    if (requestedImage == null) { 
     // Do your thing if the image is not supplied to the request URI. 
     // Throw an exception, or send 404, or show default/warning image, 
     // or just ignore it. 
     response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404. 
     return; 
    } 

    File image = //retrieve your image from the DB with the id(variable requestedImage); 

    // Check if file actually exists. 
    if (!image.exists()) { 
     // Do your thing if the file appears to be non-existing. 
     // Throw an exception, or send 404, or show default/warning image, 
     // or just ignore it. 
     image = new File(imageDir, Constants.DEFAULT_IMAGE); 
     if (!image.exists()){ 
      response.sendError(HttpServletResponse.SC_NOT_FOUND); 
     } 
    } 
    RandomAccessFile f = new RandomAccessFile(image, "rw"); 
    byte[] b = new byte[(int) f.length()]; 
    f.read(b); 
    f.close(); 
    response.reset(); 
    response.setBufferSize(DEFAULT_BUFFER_SIZE); 
    response.setContentType("image/png"); 
    response.getOutputStream().write(b); 
} 

}

現在檢索圖像在你的JSP

<img src="<c:url value="/image/?value=${id}"/>"/>