0

I am playing around with Jersey and would like to know how one should implement a "download" feature. For example let's say I have some resources under /files/ that I would like to be "downloaded" via a GET how should I do this? I already know the proper annotations and implementations for GET, PUT, POST, DELETE, but I'm not quite sure how one should treat binary data in this case. Could somebody please point me in the right direction, or show me a simple implementation? I've had a look at the jersey-samples-1.4, but I can't seem to be able to find what I am looking for.

Many thanks!

4

1 回答 1

1

您应该使用@Produces 注释来指定文件的媒体类型(pdf、zip 等)。可以在此处找到此注释的 Java 规范。

您的服务器应该返回创建的文件。例如,在核心 java 中,您可以执行以下操作:

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("path")
public StreamingOutput getFile() {
    return new StreamingOutput() {
        public void write(OutputStream out) throws IOException, WebApplicationException {
            try {
                 FileInputStream in = new FileInputStream(my_file);
                 byte[] buffer = new byte[4096];
                 int length;
                 while ((length = in.read(buffer)) > 0){
                    out.write(buffer, 0, length);
                 }
                 in.close();
            } catch (Exception e) {
                throw new WebApplicationException(e);
            }
        }
    };
}
于 2013-04-29T12:15:49.147 回答