我有一个用于文件下载的休息网络服务, 服务goto validationfilter并在生成响应之前验证用户。
这是我的休息服务响应式建设者
@GET
@Path("/logfile/{fileName}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFile(@PathParam("fileName") String fileName)
{
//get file content
ResponseBuilder response = Response.ok((Object) zipFile);
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getName() + "\"");
return response.build();
}
我正在使用jQuery ajax来使用web服务。使用this reference
通过上述refence,我可以下载我的文件,但是当我尝试打开文件时,它会提供invalid file error
。
然后我将代码修改为
$.ajax({
type: "GET",
url: "file downloading url",
contentType: "application/octet-stream",
beforeSend: function(xhr, settings){
xhr.setRequestHeader('auth', 'authparam')
},
success: function(response, status, xhr){
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1)
{
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = xhr.getResponseHeader('Content-Type');
var blob = new Blob([response], { type: type + '|| mime' });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
var a = document.createElement("a");
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
这个aso给出了invalid file error
但是当我使用swagger ui访问webservice时,会下载有效文件。