问题描述
我在我的项目中使用了Jersey API。我陷入一个需要下载文件的情况,但不是。我的代码如下 @GET
@Produces(application / download)
public Response downloadFile(){
String data = getDatas();
ResponseBuilder response = Response.ok(data);
response.header(Content-Disposition,attachment; filename = UserData.txt);
response.header(charset,UTF-8);
return Response.build();
}
我添加了所有的包,路径也很好。没有错误。
当我调用此API时,数据进入响应。我想要这个数据在一个文件和可下载的格式。
我也尝试过 @Produces(MediaType.APPLICATION_OCTET_STREAM)
。
如果错误,请更正我
我认为你没有发送你建立的回复。
首先你使用ResponseBuilder来构建resposne
ResponseBuilder response = Response.ok(data);
response.header(Content-Disposition,attachment; filename = UserData.txt);
response.header(charset,UTF-8);
然后你返回静态的 Response.build()
(注意资本 R
)对象,这是空的
你应该返回 response.build()
还应该生成 octet-stream
您的方法注释
@Produces(MediaType.APPLICATION_OCTET_STREAM)
而不是
@Produces(application / download)
参考这个问题:
I am using jersey API in my project. I stuck in a case that file needs to be downloaded but it's not. My code is as follow
@GET
@Produces("application/download")
public Response downloadFile(){
String data = getDatas();
ResponseBuilder response = Response.ok(data);
response.header("Content-Disposition","attachment;filename=UserData.txt");
response.header("charset", "UTF-8");
return Response.build();
}
I have added all the packages, paths are also fine. No Error came.
When I call this API, data comes in the response. I want this data to be in a file and in a downloadable format.
I also tried @Produces(MediaType.APPLICATION_OCTET_STREAM)
.
Please correct me if am doing wrong
I think you are not sending the response you have build.
first you're using a ResponseBuilder to build the resposne
ResponseBuilder response = Response.ok(data);
response.header("Content-Disposition","attachment;filename=UserData.txt");
response.header("charset", "UTF-8");
then you are returning the static Response.build()
(notice the capital R
) object, which is empty
you should return response.build()
also, you should produce octet-stream
in your method annotions
@Produces(MediaType.APPLICATION_OCTET_STREAM)
and not
@Produces("application/download")
refer to this question: what's the correct way to send a file from REST web service to client?
这篇关于文件没有使用JERSEY下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!