téléchargement de fichiers dans les services Web restful


Mon exigence est que je devrais envoyer un fichier zip de 10 Mo au client avec un service restful. J'ai trouvé le code dans les forums que l'envoi d'un objet StreamingOutput est le meilleur moyen, mais comment puis-je créer un objet StreamingOutput dans le code suivant:

@Path("PDF-file.pdf/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getPDF() throws Exception {
  return new StreamingOutput() {
     public void write(OutputStream output) throws IOException, WebApplicationException      
     {
        try {
            //------
        } catch (Exception e) {
            throw new WebApplicationException(e);
        }
     }
  };
}
Author: Falko, 2012-04-11

1 answers

C'est le meilleur moyen et le moyen facile pour le téléchargement de fichiers.

private static final String FILE_PATH = "d:\\Test2.zip";
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile() {
    File file = new File(FILE_PATH);
    ResponseBuilder response = Response.ok((Object) file);
    response.header("Content-Disposition", "attachment; filename=newfile.zip");
    return response.build();

}

Pour votre code comme vous l'avez demandé:

@GET
@Path("/helloWorldZip") 
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public StreamingOutput helloWorldZip() throws Exception {
    return new StreamingOutput(){
    @Override
        public void write(OutputStream arg0) throws IOException, WebApplicationException {
            // TODO Auto-generated method stub
            BufferedOutputStream bus = new BufferedOutputStream(arg0);
            try {
                //ByteArrayInputStream reader = (ByteArrayInputStream) Thread.currentThread().getContextClassLoader().getResourceAsStream();     
                //byte[] input = new byte[2048];  
                java.net.URL uri = Thread.currentThread().getContextClassLoader().getResource("");
                File file = new File("D:\\Test1.zip");
                FileInputStream fizip = new FileInputStream(file);
                byte[] buffer2 = IOUtils.toByteArray(fizip);
                bus.write(buffer2);
            } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
        }
    };
}
 26
Author: NamingException, 2015-08-10 14:13:50