问题描述
我是jersey/JAX-RS实施的新手.请在下面找到我的泽西岛客户代码以下载文件:
I Am new to jersey/JAX-RS implementation.Please find below my jersey client code to download file:
Client client = Client.create();
WebResource wr = client.resource("http://localhost:7070/upload-0.0.1-SNAPSHOT/rest/files/download");
Builder wb=wr.accept("application/json,application/pdf,text/plain,image/jpeg,application/xml,application/vnd.ms-excel");
ClientResponse clientResponse= wr.get(ClientResponse.class);
System.out.println(clientResponse.getStatus());
File res= clientResponse.getEntity(File.class);
File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");
res.renameTo(downloadfile);
FileWriter fr = new FileWriter(res);
fr.flush();
我的服务器端代码是:
@Path("/download")
@GET
@Produces({"application/pdf","text/plain","image/jpeg","application/xml","application/vnd.ms-excel"})
public Response getFile()
{
File download = new File("C://Data/Test/downloaded/empty.pdf");
ResponseBuilder response = Response.ok((Object)download);
response.header("Content-Disposition", "attachment; filename=empty.pdf");
return response.build();
}
在我的客户代码中,我得到的响应为200 OK,但是我无法将文件保存在硬盘上在下面的行中,我提到需要保存文件的路径和位置.不知道这里出了什么问题,将不胜感激.感谢您!
In my client code i am getting response as 200 OK,but i am unable to save my file on hard diskIn the below line i am mentioning the path and location where the files need to be saved.Not sure whats going wrong here,any help would be appreciated.Thanks in advance!!
File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");
推荐答案
我不知道泽西岛能否让您像在这里一样简单地回应一个文件:
I don't know if Jersey let's you simply respond with a file like you have here:
File download = new File("C://Data/Test/downloaded/empty.pdf");
ResponseBuilder response = Response.ok((Object)download);
您可以当然可以使用StreamingOutput响应从服务器发送文件,如下所示:
You can certainly use a StreamingOutput response to send the file from the server, like this:
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException,
WebApplicationException {
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
//@TODO read the file here and write to the writer
writer.flush();
}
};
return Response.ok(stream).build();
,您的客户希望读取流并将其放入文件中
and your client would expect to read a stream and put it in a file:
InputStream in = response.getEntityInputStream();
if (in != null) {
File f = new File("C://Data/test/downloaded/testnew.pdf");
//@TODO copy the in stream to the file f
System.out.println("Result size:" + f.length() + " written to " + f.getPath());
}
这篇关于泽西岛客户端下载并保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!