2016-10-03 9 views
0

この方法はMongoDBからimageIDで画像をダウンロードするために使用されましたが、ユーザがURLを要求すると画像をHTMLに表示する必要があります。 http://localhost:8080/UploadRest/webresources/files/download/file/64165Restful 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/pngimage/jpegなどを生成する必要があります。

ファイルタイプは実行時に異なる可能性があるため、@Producesここに[1]だけ注釈を付けることはできません。したがって、このようなResponseオブジェクト構築中に手動でコンテンツタイプを設定する必要があります:あなたのケースでは

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

を、あなたは、データベース内のファイル名と一緒にメディアタイプを格納する必要があります。もう1つの可能性は、ファイル拡張子のメディアタイプへのマッピングを実装することですが、メディアタイプを格納する方が柔軟性が高く、エラーが発生しにくくなります。

[1]いずれにしても、理由がある場合にのみこれを実行してください。多くのRESTチュートリアルに示されているものとは対照的に、ほとんどの場合、@Producesは省略してください。コンテナは、クライアントによって要求されたメディアタイプを生成することができます。

+0

あなたの助けてくれてありがとう、しかしあなたは答えを出そうとしている完全な原因を与えることができますか? –

関連する問題