Reputation: 786
I'm looking for a solution for storing unique file names for a web application using Java Servlet.
What I need is to render profile images in a webpage, since I decided to store only file names in the database I have only to be sure they're unique in the image folder: to achieve that I was thinking to name images and save them with a string name composed by the couple:
<user_id>_<hash>.<file-type>
In this manner I think I would be pretty sure there will be no collisions, since user_ids are already unique.
1) Is this solution sound?
2) What algorithm should I pick for this purpose?
I'd like to use it properly so code snippets would be very appreciated.
Thanks
Upvotes: 1
Views: 2081
Reputation: 57479
Why attach a hash or anything to it if its a 1 to 1 mapping? 1 user to 1 profile image, just use their id. If its a 1 to many, save the record in the database and get the id of that record and use that as the name. You might want to convert all your images to a particular image format too just to be consistent, so that wouldn't be stored in your database either.
BalusC tempfile method would work perfectly with this presented concept.
Upvotes: 0
Reputation: 1109432
You can use File#createTempFile()
wherein you specify the prefix, suffix and folder. The generated filename is guaranteed to be unique.
File file = File.createTempFile("name-", ".ext", new File("/path/to/uploads"));
// ...
No, this file won't be auto-deleted on exit or something, it's just a part of temp file generation mechanism.
Upvotes: 3
Reputation: 7335
Really simple approach would be to append System.currentTimeMillis()
to the userid. If userid is unique then it should be pretty safe.
Upvotes: 2