2016-10-03 59 views
0

這種方法用於從MongoDB的imageID下載圖像,但當用戶請求URL時需要在HTML中顯示圖像。 http://localhost:8080/UploadRest/webresources/files/download/file/64165如何從Restful java中以HTML格式顯示圖像

<img src="http://localhost:8080/UploadRest/webresources/files/download/file/64165"> 

我需要做的方法顯示無法下載

@GET 
@Path("/download/file/{id}") 
@Produces(MediaType.APPLICATION_OCTET_STREAM) 
public Response downloadFilebyID(@PathParam("id") String id) throws IOException { 

    Response response = null; 
    MongoClientURI uri = new MongoClientURI(CONNECTION_URL); 
    MongoClient mongoClient = new MongoClient(uri); 

    DB mongoDB = mongoClient.getDB(DATABASE_NAME); 

    //Let's store the standard data in regular collection 
    DBCollection collection = mongoDB.getCollection(USER_COLLECION); 

    logger.info("Inside downloadFilebyID..."); 
    logger.info("ID: " + id); 

    BasicDBObject query = new BasicDBObject(); 
    query.put("_id", id); 
    DBObject doc = collection.findOne(query); 
    DBCursor cursor = collection.find(query); 

    if (cursor.hasNext()) { 
     Set<String> allKeys = doc.keySet(); 
     HashMap<String, String> fields = new HashMap<String,String>(); 
     for (String key: allKeys) { 
      fields.put(key, doc.get(key).toString()); 
     } 

     logger.info("description: " + fields.get("description")); 
     logger.info("department: " + fields.get("department")); 
     logger.info("file_year: " + fields.get("file_year")); 
     logger.info("filename: " + fields.get("filename")); 

     GridFS fileStore = new GridFS(mongoDB, "filestore"); 
     GridFSDBFile gridFile = fileStore.findOne(query); 

     InputStream in = gridFile.getInputStream(); 

     ByteArrayOutputStream out = new ByteArrayOutputStream(); 
     int data = in.read(); 
     while (data >= 0) { 
      out.write((char) data); 
      data = in.read(); 
     } 
     out.flush(); 

     ResponseBuilder builder = Response.ok(out.toByteArray()); 
     builder.header("Content-Disposition", "attachment; filename=" + fields.get("filename")); 
     response = builder.build(); 
    } else { 
     response = Response.status(404). 
     entity(" Unable to get file with ID: " + id). 
     type("text/plain"). 
     build(); 
    } 
    return response; 
} 

回答

0

的問題是線

@Produces(MediaType.APPLICATION_OCTET_STREAM) 

這告訴你是返回一個字節流的客戶端,即字節流而不是圖像。根據圖像的文件類型,您應該生成內容類型image/png,image/jpeg或其他內容。

由於文件類型在運行時可能會有所不同,因此您不能在此簡單註釋@Produces [1]。所以,你必須手動設置內容類型,同時構建Response對象是這樣的:

Response.ok(bytes, "image/png"); 

在你的情況,你應該存儲介質類型一起在數據庫中的文件名。另一種可能性是實現文件擴展名到媒體類型的映射,但存儲媒體類型更加靈活並且不易出錯。

[1]無論如何,只有在有充足的理由時才應該這樣做;與許多REST教程中顯示的內容相反,在大多數情況下,應該省略@Produces。然後容器可以生成客戶請求的媒體類型。

+0

感謝您的幫助,但您能否給出完整的來源原因,我試着做你的答案,它給了我例外 –

相關問題