2016-10-03 58 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

感谢您的帮助,但您能否给出完整的来源原因,我试着做你的答案,它给了我例外 –