将 zip 文件从 REST 返回到客户端不弹出文件
Posted
技术标签:
【中文标题】将 zip 文件从 REST 返回到客户端不弹出文件【英文标题】:Returning zip file from REST to client not popping up the file 【发布时间】:2016-03-19 10:15:13 【问题描述】:我正在尝试通过添加 Content-Type
和 Content-Disposition
来下载从 REST 发送的 zip 文件,方法如下:
服务器端
@Produces("application/x-zip-compressed")
public Response export(@PathParam("username") String username,
@Context UriInfo ui)
long timeStamp = new Date().getTime();
String exportedFolder = "/home/madmin/pods/"+username+"/download/";
String Path = ui.getRequestUri().toString()
.replace(replaceMe + username, "");
Path = Path.replace("http://", "https://");
Path = Path.replace(",system/export", "");
String outputZipFile = exportedFolder+"exported_on_"+timeStamp+".zip";
String sourceFolder = null;
File file = new File(exportedFolder);
if (!file.exists())
if (file.mkdirs())
System.out.println("Directory is created!");
else
System.out.println("Failed to create directory for exporting!");
//return ;
constructGraphs cGraphs = new constructGraphs(Path, username);
sourceFolder = cGraphs.writeGraphFiles();
generateZipFile appZip = new generateZipFile(sourceFolder,outputZipFile);
appZip.generateFileList(new File(sourceFolder));
appZip.zipIt(outputZipFile);
//Read the outputZipFile as inputStream and return it
FileInputStream fileIs = null;
try
fileIs = new FileInputStream(outputZipFile);
catch (IOException e)
throw new WebApplicationException(404);
String fileName= outputZipFile.substring(outputZipFile.lastIndexOf("/")+1, outputZipFile.length());
return Response.status(Status.OK).entity(fileIs).header("Content-Disposition","attachment; filename = "+fileName).build();
客户端:
另一方面,客户端期望application/x-zip-compressed
如下:
$http(
method: 'GET',
url: uri,
headers:
'Accept': 'application/x-zip-compressed'
,
withCredentials: true
).
success(function(data, status, headers)
if (status == 200 || status == 201)
notify('Success', 'Node exported.');
).
error(function(data, status)
if (status == 401)
notify('Forbidden', 'Authentication required to edit the resource.');
else if (status == 403)
notify('Forbidden', 'You are not allowed to edit the resource.');
else
notify('Failed', status + " " + data);
);
文件没有弹出,而是在响应中看到输入流。
我在这里做错了什么吗?任何帮助将不胜感激。
【问题讨论】:
在返回响应之前尝试这个 response.setContentType("application/x-zip-compressed") @userRaj 检查默认情况下在标头中设置的响应,这就是为什么我不必明确地这样做。 【参考方案1】:使用 AJAX 是不可能的,我假设您在这种情况下使用的是 angularjs http 服务。见:Why threre is no way to download file using ajax request?。
您有不同的选择来解决您的问题。 例如:easiest way to open a download window without navigating away from the page 或How do you serve a file for download with AngularJS or javascript?
【讨论】:
以上是关于将 zip 文件从 REST 返回到客户端不弹出文件的主要内容,如果未能解决你的问题,请参考以下文章
DialogFragment dismiss() 不弹出回栈
Spring REST - 创建 .zip 文件并将其发送到客户端