如何在Restful java中以HTML格式显示图像

时间:2016-10-03 11:17:24

标签: java html mongodb web-services rest

此方法用于通过MongoDB中的imageID下载图像,但我需要在用户请求URL时在HTML中显示图像。 http://localhost:8080/UploadRest/webresources/files/download/file/64165

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

1 个答案:

答案 0 :(得分:0)

问题在于

@Produces(MediaType.APPLICATION_OCTET_STREAM)

这告诉客户端您正在返回八位字节流,即字节流而不是图像。根据图片的文件类型,您应该生成内容类型image/pngimage/jpeg或其他。

由于文件类型在运行时可能会有所不同,因此您不能简单地在此处注释@Produces [1]。因此,您必须在构建Response对象时手动设置内容类型,如下所示:

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

在您的情况下,您应该将媒体类型与文件名一起存储在数据库中。另一种可能性是实现文件扩展名到媒体类型的映射,但存储媒体类型更灵活,更不容易出错。

[1]无论如何,只有在有充分理由这样做时才应该这样做;与许多REST教程中显示的内容相反,在大多数情况下,您应该省略@Produces。然后,容器可以生成客户端请求的媒体类型。