Quote:
Originally Posted by emmoplayer
Hey alle zusammen.
Ich sitze seit Tagen an einem Problem was ich einfach nicht gelöst bekomme.
Ich nutze MongoDB als meine Datenbank und speichere Bilder über GridFS ab.
Leider kriege ich nicht über MongoDB eine Art URL zu den Bildern, die über GridFS abgespeichert worden sind.
Gibt es eine Möglichkeit, mit Hilfe des DownloadToStream/OpenDownloadStream eine URL zu ersetzen?
Leider konnte ich bei den Java Drivern nichts passendes finden.
Vielen Dank im Voraus.
|
I don't know what you mean by URL, im assuming you want your asset data url.
Code:
// Obtain asset DATA url
public String obtainFileUrl(GridFSBucket bucket, String fileNameOrId) {
// open download stream
GridFSDownloadStream downloadStream = bucket.openDownloadStream(fileNameOrId);
// get file info, we need content type and file size
GridFSFile file = downloadStream.getGridFSFile();
// get content type
org.bson.Document metadata = file.getMetadata();
// if content type of asset is not stored as this key, change it
String contentType = metadata.getString("contentType");
// create byte buffer to read our stream
// this can be bad if files are too big or memory is limited so be careful
byte[] raw = new byte[(int)file.getLength()];
downloadStream.read(raw);
downloadStream.close();
// encode asset raw bytes to base64 string
String base64EncodedAsset = Base64.getEncoder().encodeToString(raw);
// create data url
String url = String.format("data:%s;base64,%s", contentType, base64EncodedAsset);
return url;
}
This can be overhead if your api or whatever is consuming assets a lot.
Another solution: -> DownloadToStream to a file in a temp folder (with a hash or sth) and send back that file, every time a file needs to be consumed you check in your temp folder if a the file exits otherwise it creates the new one. (This strategy needs to flush unused files from time to time to prevent eating your disk space)