dazzle
dazzle

Reputation: 243

java logic help in saving images

I have a word cloud app which generates a image based upon user input text. This generated image is stored in images folder. I have provided a save image option which allows user to save this image on their desktop. I am doing this by calling a servlet shown below which reads the image stored & writes to byte stream.

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setHeader("Content-disposition","attachment; filename=output.png");

    String filename = request.getSession().getServletContext().getRealPath("/")+"/images/output.png";
    String mimeType = "image/png";
    response.setContentType(mimeType);

    File file = new File(filename);
    response.setContentLength((int)file.length());
    FileInputStream in = new FileInputStream(file);
    OutputStream outputStream = response.getOutputStream();

    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
        outputStream.write(buf, 0, count);
    }
    in.close();
    outputStream.close();


} 

Problem with this approach is, if another user (user 2) meantime generates a word cloud, it replaces output.png with this new image. Now if user 1 tries to save the image, he gets an wrong image(image of user 2).

Can you please suggest me a better approach which will allow to keep images user specific?

Upvotes: 0

Views: 332

Answers (3)

David Weiser
David Weiser

Reputation: 5195

Rename output.png with something like <username>.png

Upvotes: 0

Thomas
Thomas

Reputation: 88707

Pass the username or another unique string in the request to use for the filename.

... image based upon user input text ...

You could also generate the filename from that input text, thus you could try and cache the image per text and reuse an already generated image for the same text (if that is appropriate in your case).

Upvotes: 1

Vivien Barousse
Vivien Barousse

Reputation: 20875

How about generating a unique file name for the image, instead of using all the time the same one?

The file name can then be stored in the user's session, or passed to the second Servlet as URL parameter. This allows a huge amount of user to generate images (as long as your file names are really unique), and still uses a disk-based approach.

You could as well store images directly in the user session, but that would consume a lot of memory, and not all users would use the "Save on desktop" feature.

Edit: Also, when you'll decide what approach you are taking to implement this, remember that a user can also generate two images at the same time (if he opens your service in two tabs, for example). I think a truly unique file name is better than the username in this case.

Upvotes: 4

Related Questions