I have a rest web service for file download, The service goto validationfilter and validate the user before generating the response.
this is my rest service responsebuilder
@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();
}
I am consuming the webservice using jQuery ajax. this reference is used
By above refence I am able to download my file but when I am trying to open file it gives invalid file error
.
then I modified the code to
$.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
this aso gives invalid file error
But when I access webservice using swagger ui, valid file is downloaded.