0

I'm working on a chat application, and I need to process a get request for a file that has been uploaded to the database. I'm not sure if I should return an output stream or a file or what.

The idea is that it will be something like any other chat application where the image appears as message are loaded. Using an output stream seemed like the best option, but I wasn't sure how to create the output stream from the information in the database, which includes an id, checksum, name, size, and mime type.

So my questions are:

  1. How should I approach this?

  2. if output stream is the best way, what's the ideal way to implement it?

Any guidance is appreciated, please let me know if I can make the question more clear, or if more details are necessary to answer the question.

Martin G
  • 17,357
  • 9
  • 82
  • 98
  • 1
    http://stackoverflow.com/questions/8623709/output-an-image-file-from-a-servlet – Romski May 22 '15 at 03:00
  • @Romski, I don't think that's quite the same, but if it is, could you explain? The main difference is there the image is being read from a disk, not the server/database. –  May 22 '15 at 03:07
  • 2
    Where the image comes from is not important as the contents will be the same. To serve the image to a client you will need some form of server technology like Servlets. – Romski May 22 '15 at 03:10

1 Answers1

0

What I couldn't understand how to do is this: serve the image to the front-end/client code. As it turns out, it was super easy.

    @GET @javax.ws.rs.Path("/file/{fileId}")
    public Response getFile(@Context SecurityContext sc, @PathParam("id") long topicId, @PathParam("fileId") long fileId) {

    TopicFile tFile = topicAccessor.getFile(fileId);

    String fileLocation = "/server/uploads/" + tFile.getChecksum();

    File file = new File(fileLocation);

    return Response.ok(file, tFile.getType()).build();

}

Here TopicFile holds metadata for the file in the database, and the files are named their checksum.

So basically the solution to my problem was to return a Response. I hadn't thought of this earlier because I "inherited" this code, and I trusted that the previous person had god reason not to use the Response class.