0

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.

Hitesh Ghuge
  • 793
  • 2
  • 10
  • 39
  • First of all, open the downloaded file in a text or hex editor, and check what it actually contains – there might be error messages in there perhaps, output by the server. – CBroe Jun 15 '18 at 12:12
  • file I am trying to download is zip file. – Hitesh Ghuge Jun 15 '18 at 12:16
  • the response of web service and proper zip file open in text editor both the content are same. – Hitesh Ghuge Jun 15 '18 at 12:18
  • Then try a hex editor, just to be sure. It might be something trivial like a BOM that got added accidentally … – CBroe Jun 15 '18 at 12:20
  • `type: type + '|| mime'`? What does that `'|| mime'` string would do in the MIMEType? Also, your response is utf-8 text, so your binary data certainly got mangled. `contentType` doesn't set the content type of the response, but of the sent data. What you want is to perform an `xhr.responseType = 'blob'` or `'arrayBuffer'` request, this way you will have your binary data non-corrupted. As to how to do it with jQuery... IMM it's better to use raw API, (always found jQuery added more overhead for ajax...) – Kaiido Jun 15 '18 at 12:24
  • '|| mime' i found in some solution. – Hitesh Ghuge Jun 15 '18 at 12:29
  • Not able to find `xhr.responseType`. – Hitesh Ghuge Jun 15 '18 at 12:35
  • As a string? Never saw that and I guess it would make any MIME type validator scream outright, but anyway your problem is not here. For xhr.responseType => https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType Or if you target newer browsers, you could also just do `fetch(url, headers).then(r=>r.blob())` – Kaiido Jun 15 '18 at 12:35

0 Answers0