【发布时间】:2014-04-14 10:18:00
【问题描述】:
我正在尝试使用 restful 服务在 java 中创建和下载一个 zip 文件。但它不适合我。请在下面找到代码:
@GET
@Path("/exportZip")
@Produces("application/zip")
public Response download(@QueryParam("dim") final String dimId,
@QueryParam("client") final String clientId,
@QueryParam("type") final String type,
@Context UriInfo ui) {
System.out.println("Start");
ResponseBuilder response = null ;
String filetype = "";
if(type.equalsIgnoreCase("u")){
filetype = "UnMapped";
}else if(type.equalsIgnoreCase("m")){
filetype = "Mapped";
}
try {
byte[] workbook = null;
workbook = engineService.export(dim, client, type);
InputStream is = new ByteArrayInputStream(workbook);
FileOutputStream out = new FileOutputStream(filetype + "tmp.zip");
int bufferSize = 1024;
byte[] buf = new byte[bufferSize];
int n = is.read(buf);
while (n >= 0) {
out.write(buf, 0, n);
n = is.read(buf);
}
response = Response.ok((Object) out);
response.header("Content-Disposition",
"attachment; filename=\"" + filetype + " - " + new Date().toString() + ".zip\"");
out.flush();
out.close();
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("End");
return response.build();
}
这给了我以下错误: javax.ws.rs.WebApplicationException:com.sun.jersey.api.MessageException:Java 类 java.io.FileOutputStream、Java 类型类 java.io.FileOutputStream 和 MIME 媒体类型 application/zip 的消息正文编写器不是找到了
【问题讨论】:
-
为什么要将 FileOutputStream 设置为响应正文?
-
@Gimby 你是对的。我删除了那个位,我只是将字节数组作为 Response.ok((object) workbook) 传递给响应。并且 zip 文件是可下载的。