Binary files corrupted - How to Download Binary Files with AngularJSFile is corrupted while downloading using angular $httpHow to download a zip file in AngularJS / FilesaverJSHow to display a binary image in HTML using AngularJSmpdf working in postman but not in chromeWhere would I set the responseType?download file from server side using angularjs but file format are changed?PDF file gets corrupted if data is acquired through $http.get() but remains intact if acquired through $http.post() in AngularHow to make the browser download a file and provide a custom header?Why the file cannot be save properly?does angularjs have some tech like fetch().blobDownload a file with Android, and showing the progress in a ProgressDialogHow does data binding work in AngularJS?'this' vs $scope in AngularJS controllersHow do I access the $scope variable in browser's console using AngularJS?What are the nuances of scope prototypal / prototypical inheritance in AngularJS?What is the difference between '@' and '=' in directive scope in AngularJS?“Thinking in AngularJS” if I have a jQuery background?How do I use $scope.$watch and $scope.$apply in AngularJS?AngularJS: Service vs provider vs factoryDownloading multiple files using AngularJS and storing in path

Taking my Ph.D. advisor out for dinner after graduation

How do amateur satellites stay consistently in the amateur-sat bands acoss the globe?

Is there a minimum amount of electricity that can be fed back into the grid?

What purpose does mercury dichloride have in fireworks?

Any way to meet code with 40.7% or 40.44% conduit fill?

How can I use my cell phone's light as a reading light?

What's the difference between a type and a kind?

What are some bad ways to subvert tropes?

Are "confidant" and "confident" homophones?

Is this car delivery via Ebay Motors on Craigslist a scam?

Can you create a free-floating MASYU puzzle?

What happens if the limit of 4 billion files was exceeded in an ext4 partition?

Minor differences between two recorded guitars

How to find the version of extensions used on a Joomla website without access to the backend?

How do resistors generate different heat if we make the current fixed and changed the voltage and resistance? Notice the flow of charge is constant

Multi-user CRUD: Valid, Problem, or Error?

Why do Martians have to wear space helmets?

comparing two addresses

Why does "sattsehen" take accusative "mich", not dative "mir"? Even though it is not "me" that I'm looking at?

Why do we need a bootloader separate from our application program in microcontrollers?

Did William Shakespeare hide things in his writings?

How did Einstein know the speed of light was constant?

As a supervisor, what feedback would you expect from a PhD who quits?

Why does this function pointer assignment work when assigned directly but not with the conditional operator?



Binary files corrupted - How to Download Binary Files with AngularJS


File is corrupted while downloading using angular $httpHow to download a zip file in AngularJS / FilesaverJSHow to display a binary image in HTML using AngularJSmpdf working in postman but not in chromeWhere would I set the responseType?download file from server side using angularjs but file format are changed?PDF file gets corrupted if data is acquired through $http.get() but remains intact if acquired through $http.post() in AngularHow to make the browser download a file and provide a custom header?Why the file cannot be save properly?does angularjs have some tech like fetch().blobDownload a file with Android, and showing the progress in a ProgressDialogHow does data binding work in AngularJS?'this' vs $scope in AngularJS controllersHow do I access the $scope variable in browser's console using AngularJS?What are the nuances of scope prototypal / prototypical inheritance in AngularJS?What is the difference between '@' and '=' in directive scope in AngularJS?“Thinking in AngularJS” if I have a jQuery background?How do I use $scope.$watch and $scope.$apply in AngularJS?AngularJS: Service vs provider vs factoryDownloading multiple files using AngularJS and storing in path






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3















download any file using ResponseEntity with angular does not work



I need to download a file using angular in client side,
this file can have any format it could be a pdf or excel or image or txt ...
my method works just for txt files and gives me a fail format for excel and image and for the pdf it gives an empty pdf.



so in my controller here is the function that calles the service method:



 vm.downloadFile = downloadFile;

function downloadFile(file)
var urlDir = "C://STCI//"+idpeticion;
return VerDocServices.downloadFile(file,urlDir)
.then(function(response)
var data = response.data;
var filename = file;
var contentType = 'application/octet-stream';//octet-stream
var linkElement = document.createElement('a');
try
var blob = new Blob([ data ],
type : contentType
);
var url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
linkElement.setAttribute("download", filename);
var clickEvent = new MouseEvent("click",
"view" : window,
"bubbles" : true,
"cancelable" : false
);
linkElement.dispatchEvent(clickEvent);
catch (ex)
console.log(ex);
throw ex;

).catch(function(response)
alert('Se ha producido un error al exportar del documento');
console.log(response.status);
throw response;
);



and my service.js has:



angular.module('mecenzApp').service('VerDocServices',['$http',function($http) 

this.downloadFile = function(file,urlDir)

return $http.get('api/downloadFile',
params :
file : file,
urlDir : urlDir

); ]);


And my service method is this:



@GetMapping("/downloadFile")
@Timed
public ResponseEntity<byte[]> downloadFile(@RequestParam(value = "file") String file, @RequestParam(value = "urlDir") String urlDir)
log.debug("GET ---------------- DOWNLOAD FILE : ", file);
log.debug("GET ---------------- From the DIRECTORY: ",urlDir);

InputStream fileStream;
String filepath = urlDir+File.separator+file;
try
File f = new File(filepath);
log.debug("GET ---------------- FILE: ",f.getPath());
fileStream = new FileInputStream(f);
byte[] contents = IOUtils.toByteArray(fileStream);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/octet-stream"));
String filename = file;
headers.setContentDispositionFormData(filename, filename);
ResponseEntity<byte[]> response2 = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
fileStream.close();
return response2;

catch (FileNotFoundException e)
System.err.println(e);
catch (IOException e)
System.err.println(e);

return null;



could you plz take a look and tell me what did I have missed??



Thank youuu :)










share|improve this question






























    3















    download any file using ResponseEntity with angular does not work



    I need to download a file using angular in client side,
    this file can have any format it could be a pdf or excel or image or txt ...
    my method works just for txt files and gives me a fail format for excel and image and for the pdf it gives an empty pdf.



    so in my controller here is the function that calles the service method:



     vm.downloadFile = downloadFile;

    function downloadFile(file)
    var urlDir = "C://STCI//"+idpeticion;
    return VerDocServices.downloadFile(file,urlDir)
    .then(function(response)
    var data = response.data;
    var filename = file;
    var contentType = 'application/octet-stream';//octet-stream
    var linkElement = document.createElement('a');
    try
    var blob = new Blob([ data ],
    type : contentType
    );
    var url = window.URL.createObjectURL(blob);
    linkElement.setAttribute('href', url);
    linkElement.setAttribute("download", filename);
    var clickEvent = new MouseEvent("click",
    "view" : window,
    "bubbles" : true,
    "cancelable" : false
    );
    linkElement.dispatchEvent(clickEvent);
    catch (ex)
    console.log(ex);
    throw ex;

    ).catch(function(response)
    alert('Se ha producido un error al exportar del documento');
    console.log(response.status);
    throw response;
    );



    and my service.js has:



    angular.module('mecenzApp').service('VerDocServices',['$http',function($http) 

    this.downloadFile = function(file,urlDir)

    return $http.get('api/downloadFile',
    params :
    file : file,
    urlDir : urlDir

    ); ]);


    And my service method is this:



    @GetMapping("/downloadFile")
    @Timed
    public ResponseEntity<byte[]> downloadFile(@RequestParam(value = "file") String file, @RequestParam(value = "urlDir") String urlDir)
    log.debug("GET ---------------- DOWNLOAD FILE : ", file);
    log.debug("GET ---------------- From the DIRECTORY: ",urlDir);

    InputStream fileStream;
    String filepath = urlDir+File.separator+file;
    try
    File f = new File(filepath);
    log.debug("GET ---------------- FILE: ",f.getPath());
    fileStream = new FileInputStream(f);
    byte[] contents = IOUtils.toByteArray(fileStream);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/octet-stream"));
    String filename = file;
    headers.setContentDispositionFormData(filename, filename);
    ResponseEntity<byte[]> response2 = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
    fileStream.close();
    return response2;

    catch (FileNotFoundException e)
    System.err.println(e);
    catch (IOException e)
    System.err.println(e);

    return null;



    could you plz take a look and tell me what did I have missed??



    Thank youuu :)










    share|improve this question


























      3












      3








      3


      1






      download any file using ResponseEntity with angular does not work



      I need to download a file using angular in client side,
      this file can have any format it could be a pdf or excel or image or txt ...
      my method works just for txt files and gives me a fail format for excel and image and for the pdf it gives an empty pdf.



      so in my controller here is the function that calles the service method:



       vm.downloadFile = downloadFile;

      function downloadFile(file)
      var urlDir = "C://STCI//"+idpeticion;
      return VerDocServices.downloadFile(file,urlDir)
      .then(function(response)
      var data = response.data;
      var filename = file;
      var contentType = 'application/octet-stream';//octet-stream
      var linkElement = document.createElement('a');
      try
      var blob = new Blob([ data ],
      type : contentType
      );
      var url = window.URL.createObjectURL(blob);
      linkElement.setAttribute('href', url);
      linkElement.setAttribute("download", filename);
      var clickEvent = new MouseEvent("click",
      "view" : window,
      "bubbles" : true,
      "cancelable" : false
      );
      linkElement.dispatchEvent(clickEvent);
      catch (ex)
      console.log(ex);
      throw ex;

      ).catch(function(response)
      alert('Se ha producido un error al exportar del documento');
      console.log(response.status);
      throw response;
      );



      and my service.js has:



      angular.module('mecenzApp').service('VerDocServices',['$http',function($http) 

      this.downloadFile = function(file,urlDir)

      return $http.get('api/downloadFile',
      params :
      file : file,
      urlDir : urlDir

      ); ]);


      And my service method is this:



      @GetMapping("/downloadFile")
      @Timed
      public ResponseEntity<byte[]> downloadFile(@RequestParam(value = "file") String file, @RequestParam(value = "urlDir") String urlDir)
      log.debug("GET ---------------- DOWNLOAD FILE : ", file);
      log.debug("GET ---------------- From the DIRECTORY: ",urlDir);

      InputStream fileStream;
      String filepath = urlDir+File.separator+file;
      try
      File f = new File(filepath);
      log.debug("GET ---------------- FILE: ",f.getPath());
      fileStream = new FileInputStream(f);
      byte[] contents = IOUtils.toByteArray(fileStream);
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.parseMediaType("application/octet-stream"));
      String filename = file;
      headers.setContentDispositionFormData(filename, filename);
      ResponseEntity<byte[]> response2 = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
      fileStream.close();
      return response2;

      catch (FileNotFoundException e)
      System.err.println(e);
      catch (IOException e)
      System.err.println(e);

      return null;



      could you plz take a look and tell me what did I have missed??



      Thank youuu :)










      share|improve this question
















      download any file using ResponseEntity with angular does not work



      I need to download a file using angular in client side,
      this file can have any format it could be a pdf or excel or image or txt ...
      my method works just for txt files and gives me a fail format for excel and image and for the pdf it gives an empty pdf.



      so in my controller here is the function that calles the service method:



       vm.downloadFile = downloadFile;

      function downloadFile(file)
      var urlDir = "C://STCI//"+idpeticion;
      return VerDocServices.downloadFile(file,urlDir)
      .then(function(response)
      var data = response.data;
      var filename = file;
      var contentType = 'application/octet-stream';//octet-stream
      var linkElement = document.createElement('a');
      try
      var blob = new Blob([ data ],
      type : contentType
      );
      var url = window.URL.createObjectURL(blob);
      linkElement.setAttribute('href', url);
      linkElement.setAttribute("download", filename);
      var clickEvent = new MouseEvent("click",
      "view" : window,
      "bubbles" : true,
      "cancelable" : false
      );
      linkElement.dispatchEvent(clickEvent);
      catch (ex)
      console.log(ex);
      throw ex;

      ).catch(function(response)
      alert('Se ha producido un error al exportar del documento');
      console.log(response.status);
      throw response;
      );



      and my service.js has:



      angular.module('mecenzApp').service('VerDocServices',['$http',function($http) 

      this.downloadFile = function(file,urlDir)

      return $http.get('api/downloadFile',
      params :
      file : file,
      urlDir : urlDir

      ); ]);


      And my service method is this:



      @GetMapping("/downloadFile")
      @Timed
      public ResponseEntity<byte[]> downloadFile(@RequestParam(value = "file") String file, @RequestParam(value = "urlDir") String urlDir)
      log.debug("GET ---------------- DOWNLOAD FILE : ", file);
      log.debug("GET ---------------- From the DIRECTORY: ",urlDir);

      InputStream fileStream;
      String filepath = urlDir+File.separator+file;
      try
      File f = new File(filepath);
      log.debug("GET ---------------- FILE: ",f.getPath());
      fileStream = new FileInputStream(f);
      byte[] contents = IOUtils.toByteArray(fileStream);
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.parseMediaType("application/octet-stream"));
      String filename = file;
      headers.setContentDispositionFormData(filename, filename);
      ResponseEntity<byte[]> response2 = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
      fileStream.close();
      return response2;

      catch (FileNotFoundException e)
      System.err.println(e);
      catch (IOException e)
      System.err.println(e);

      return null;



      could you plz take a look and tell me what did I have missed??



      Thank youuu :)







      angularjs download angularjs-http






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Aug 28 '17 at 15:02









      georgeawg

      37.5k11 gold badges56 silver badges73 bronze badges




      37.5k11 gold badges56 silver badges73 bronze badges










      asked Jan 16 '17 at 9:01









      SmahaneSmahane

      551 silver badge10 bronze badges




      551 silver badge10 bronze badges






















          2 Answers
          2






          active

          oldest

          votes


















          6














          How to Download Binary Files with AngularJS



          When downloading binary files, it is important to set the responseType:



          app.service('VerDocServices',['$http',function($http) 

          this.downloadFile = function(url, file, urlDir)
          var config =
          //SET responseType
          responseType: 'blob',
          params :
          file : file,
          urlDir : urlDir

          ;

          return $http.get(url, config)
          .then(function(response)
          return response.data;
          ).catch(function(response)
          console.log("ERROR: ", response.status);
          throw response;
          );
          ;
          ]);


          If the responseType is omitted the XHR API defaults to converting UTF-8 encoded text to DOMString (UTF-16) which will corrupt PDF, image, and other binary files.



          For more information, see MDN Web API Reference - XHR ResponseType






          share|improve this answer

























          • you are just AMAZINNNG ! thank youuuuuuuuuuuuuuuuu :D

            – Smahane
            Jan 16 '17 at 17:56


















          1














          I don't know much about the backend, but I'll provide what i have used may be it will help, so On the Java Script File:



          //your $http(request...)

          .success(function (data, status, headers, config)
          //Recieves base64 String data
          var fileName = 'My Awesome File Name'+'.'+'pdf';

          //Parsing base64 String...
          var binaryString = window.atob(data);
          var binaryLen = binaryString.length;
          var fileContent = new Uint8Array(binaryLen);
          for (var i = 0; i < binaryLen; i++)
          var ascii = binaryString.charCodeAt(i);
          fileContent[i] = ascii;

          var blob = new Blob([fileContent], type: 'application/octet-stream' ); //octet-stream
          var fileURL = window.URL.createObjectURL(blob);
          $sce.trustAsResourceUrl(fileURL); //allow angular to trust this url
          //Creating the anchor download link
          var anchor = angular.element('<a/>');
          anchor.css(display: 'none'); // Make sure it's not visible
          angular.element(document.body).append(anchor); // Attach it to the document
          anchor.attr(
          href: fileURL,
          target: '_blank',
          download: fileName
          )[0].click();
          anchor.remove(); // Clean it up afterwards
          )
          //.error(function(...


          And On your backend, make sure that your webservice produces octet-stream and returning the file in base64 data format, i did this using Java JAX-RS like this:



          @POST
          @Path("/downloadfile")
          @Consumes(MediaType.APPLICATION_JSON)
          @Produces(MediaType.APPLICATION_OCTET_STREAM)
          public Response downloadFile(...)
          String base64String = Base64.getEncoder().encodeToString(/*here you pass your file in byte[] format*/);
          return Response.ok(base64String).build();






          share|improve this answer



























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41672656%2fbinary-files-corrupted-how-to-download-binary-files-with-angularjs%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            6














            How to Download Binary Files with AngularJS



            When downloading binary files, it is important to set the responseType:



            app.service('VerDocServices',['$http',function($http) 

            this.downloadFile = function(url, file, urlDir)
            var config =
            //SET responseType
            responseType: 'blob',
            params :
            file : file,
            urlDir : urlDir

            ;

            return $http.get(url, config)
            .then(function(response)
            return response.data;
            ).catch(function(response)
            console.log("ERROR: ", response.status);
            throw response;
            );
            ;
            ]);


            If the responseType is omitted the XHR API defaults to converting UTF-8 encoded text to DOMString (UTF-16) which will corrupt PDF, image, and other binary files.



            For more information, see MDN Web API Reference - XHR ResponseType






            share|improve this answer

























            • you are just AMAZINNNG ! thank youuuuuuuuuuuuuuuuu :D

              – Smahane
              Jan 16 '17 at 17:56















            6














            How to Download Binary Files with AngularJS



            When downloading binary files, it is important to set the responseType:



            app.service('VerDocServices',['$http',function($http) 

            this.downloadFile = function(url, file, urlDir)
            var config =
            //SET responseType
            responseType: 'blob',
            params :
            file : file,
            urlDir : urlDir

            ;

            return $http.get(url, config)
            .then(function(response)
            return response.data;
            ).catch(function(response)
            console.log("ERROR: ", response.status);
            throw response;
            );
            ;
            ]);


            If the responseType is omitted the XHR API defaults to converting UTF-8 encoded text to DOMString (UTF-16) which will corrupt PDF, image, and other binary files.



            For more information, see MDN Web API Reference - XHR ResponseType






            share|improve this answer

























            • you are just AMAZINNNG ! thank youuuuuuuuuuuuuuuuu :D

              – Smahane
              Jan 16 '17 at 17:56













            6












            6








            6







            How to Download Binary Files with AngularJS



            When downloading binary files, it is important to set the responseType:



            app.service('VerDocServices',['$http',function($http) 

            this.downloadFile = function(url, file, urlDir)
            var config =
            //SET responseType
            responseType: 'blob',
            params :
            file : file,
            urlDir : urlDir

            ;

            return $http.get(url, config)
            .then(function(response)
            return response.data;
            ).catch(function(response)
            console.log("ERROR: ", response.status);
            throw response;
            );
            ;
            ]);


            If the responseType is omitted the XHR API defaults to converting UTF-8 encoded text to DOMString (UTF-16) which will corrupt PDF, image, and other binary files.



            For more information, see MDN Web API Reference - XHR ResponseType






            share|improve this answer















            How to Download Binary Files with AngularJS



            When downloading binary files, it is important to set the responseType:



            app.service('VerDocServices',['$http',function($http) 

            this.downloadFile = function(url, file, urlDir)
            var config =
            //SET responseType
            responseType: 'blob',
            params :
            file : file,
            urlDir : urlDir

            ;

            return $http.get(url, config)
            .then(function(response)
            return response.data;
            ).catch(function(response)
            console.log("ERROR: ", response.status);
            throw response;
            );
            ;
            ]);


            If the responseType is omitted the XHR API defaults to converting UTF-8 encoded text to DOMString (UTF-16) which will corrupt PDF, image, and other binary files.



            For more information, see MDN Web API Reference - XHR ResponseType







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Aug 28 '17 at 14:45

























            answered Jan 16 '17 at 17:12









            georgeawggeorgeawg

            37.5k11 gold badges56 silver badges73 bronze badges




            37.5k11 gold badges56 silver badges73 bronze badges












            • you are just AMAZINNNG ! thank youuuuuuuuuuuuuuuuu :D

              – Smahane
              Jan 16 '17 at 17:56

















            • you are just AMAZINNNG ! thank youuuuuuuuuuuuuuuuu :D

              – Smahane
              Jan 16 '17 at 17:56
















            you are just AMAZINNNG ! thank youuuuuuuuuuuuuuuuu :D

            – Smahane
            Jan 16 '17 at 17:56





            you are just AMAZINNNG ! thank youuuuuuuuuuuuuuuuu :D

            – Smahane
            Jan 16 '17 at 17:56













            1














            I don't know much about the backend, but I'll provide what i have used may be it will help, so On the Java Script File:



            //your $http(request...)

            .success(function (data, status, headers, config)
            //Recieves base64 String data
            var fileName = 'My Awesome File Name'+'.'+'pdf';

            //Parsing base64 String...
            var binaryString = window.atob(data);
            var binaryLen = binaryString.length;
            var fileContent = new Uint8Array(binaryLen);
            for (var i = 0; i < binaryLen; i++)
            var ascii = binaryString.charCodeAt(i);
            fileContent[i] = ascii;

            var blob = new Blob([fileContent], type: 'application/octet-stream' ); //octet-stream
            var fileURL = window.URL.createObjectURL(blob);
            $sce.trustAsResourceUrl(fileURL); //allow angular to trust this url
            //Creating the anchor download link
            var anchor = angular.element('<a/>');
            anchor.css(display: 'none'); // Make sure it's not visible
            angular.element(document.body).append(anchor); // Attach it to the document
            anchor.attr(
            href: fileURL,
            target: '_blank',
            download: fileName
            )[0].click();
            anchor.remove(); // Clean it up afterwards
            )
            //.error(function(...


            And On your backend, make sure that your webservice produces octet-stream and returning the file in base64 data format, i did this using Java JAX-RS like this:



            @POST
            @Path("/downloadfile")
            @Consumes(MediaType.APPLICATION_JSON)
            @Produces(MediaType.APPLICATION_OCTET_STREAM)
            public Response downloadFile(...)
            String base64String = Base64.getEncoder().encodeToString(/*here you pass your file in byte[] format*/);
            return Response.ok(base64String).build();






            share|improve this answer





























              1














              I don't know much about the backend, but I'll provide what i have used may be it will help, so On the Java Script File:



              //your $http(request...)

              .success(function (data, status, headers, config)
              //Recieves base64 String data
              var fileName = 'My Awesome File Name'+'.'+'pdf';

              //Parsing base64 String...
              var binaryString = window.atob(data);
              var binaryLen = binaryString.length;
              var fileContent = new Uint8Array(binaryLen);
              for (var i = 0; i < binaryLen; i++)
              var ascii = binaryString.charCodeAt(i);
              fileContent[i] = ascii;

              var blob = new Blob([fileContent], type: 'application/octet-stream' ); //octet-stream
              var fileURL = window.URL.createObjectURL(blob);
              $sce.trustAsResourceUrl(fileURL); //allow angular to trust this url
              //Creating the anchor download link
              var anchor = angular.element('<a/>');
              anchor.css(display: 'none'); // Make sure it's not visible
              angular.element(document.body).append(anchor); // Attach it to the document
              anchor.attr(
              href: fileURL,
              target: '_blank',
              download: fileName
              )[0].click();
              anchor.remove(); // Clean it up afterwards
              )
              //.error(function(...


              And On your backend, make sure that your webservice produces octet-stream and returning the file in base64 data format, i did this using Java JAX-RS like this:



              @POST
              @Path("/downloadfile")
              @Consumes(MediaType.APPLICATION_JSON)
              @Produces(MediaType.APPLICATION_OCTET_STREAM)
              public Response downloadFile(...)
              String base64String = Base64.getEncoder().encodeToString(/*here you pass your file in byte[] format*/);
              return Response.ok(base64String).build();






              share|improve this answer



























                1












                1








                1







                I don't know much about the backend, but I'll provide what i have used may be it will help, so On the Java Script File:



                //your $http(request...)

                .success(function (data, status, headers, config)
                //Recieves base64 String data
                var fileName = 'My Awesome File Name'+'.'+'pdf';

                //Parsing base64 String...
                var binaryString = window.atob(data);
                var binaryLen = binaryString.length;
                var fileContent = new Uint8Array(binaryLen);
                for (var i = 0; i < binaryLen; i++)
                var ascii = binaryString.charCodeAt(i);
                fileContent[i] = ascii;

                var blob = new Blob([fileContent], type: 'application/octet-stream' ); //octet-stream
                var fileURL = window.URL.createObjectURL(blob);
                $sce.trustAsResourceUrl(fileURL); //allow angular to trust this url
                //Creating the anchor download link
                var anchor = angular.element('<a/>');
                anchor.css(display: 'none'); // Make sure it's not visible
                angular.element(document.body).append(anchor); // Attach it to the document
                anchor.attr(
                href: fileURL,
                target: '_blank',
                download: fileName
                )[0].click();
                anchor.remove(); // Clean it up afterwards
                )
                //.error(function(...


                And On your backend, make sure that your webservice produces octet-stream and returning the file in base64 data format, i did this using Java JAX-RS like this:



                @POST
                @Path("/downloadfile")
                @Consumes(MediaType.APPLICATION_JSON)
                @Produces(MediaType.APPLICATION_OCTET_STREAM)
                public Response downloadFile(...)
                String base64String = Base64.getEncoder().encodeToString(/*here you pass your file in byte[] format*/);
                return Response.ok(base64String).build();






                share|improve this answer















                I don't know much about the backend, but I'll provide what i have used may be it will help, so On the Java Script File:



                //your $http(request...)

                .success(function (data, status, headers, config)
                //Recieves base64 String data
                var fileName = 'My Awesome File Name'+'.'+'pdf';

                //Parsing base64 String...
                var binaryString = window.atob(data);
                var binaryLen = binaryString.length;
                var fileContent = new Uint8Array(binaryLen);
                for (var i = 0; i < binaryLen; i++)
                var ascii = binaryString.charCodeAt(i);
                fileContent[i] = ascii;

                var blob = new Blob([fileContent], type: 'application/octet-stream' ); //octet-stream
                var fileURL = window.URL.createObjectURL(blob);
                $sce.trustAsResourceUrl(fileURL); //allow angular to trust this url
                //Creating the anchor download link
                var anchor = angular.element('<a/>');
                anchor.css(display: 'none'); // Make sure it's not visible
                angular.element(document.body).append(anchor); // Attach it to the document
                anchor.attr(
                href: fileURL,
                target: '_blank',
                download: fileName
                )[0].click();
                anchor.remove(); // Clean it up afterwards
                )
                //.error(function(...


                And On your backend, make sure that your webservice produces octet-stream and returning the file in base64 data format, i did this using Java JAX-RS like this:



                @POST
                @Path("/downloadfile")
                @Consumes(MediaType.APPLICATION_JSON)
                @Produces(MediaType.APPLICATION_OCTET_STREAM)
                public Response downloadFile(...)
                String base64String = Base64.getEncoder().encodeToString(/*here you pass your file in byte[] format*/);
                return Response.ok(base64String).build();







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 16 '17 at 9:52

























                answered Jan 16 '17 at 9:46









                Mostafa OmarMostafa Omar

                1121 silver badge5 bronze badges




                1121 silver badge5 bronze badges



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f41672656%2fbinary-files-corrupted-how-to-download-binary-files-with-angularjs%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현