简体   繁体   中英

How to retrieve file from database for use by front-end code? (rest using java and jersey)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM