Wednesday, April 6, 2016

Download a file via javascript

Today I had an interesting challenge. I had to download a file in javascript. Why through javascript and not through a link or a form post?

  • I had to set a custom accept header to get the file into a specific format (in my case in excel format)
  • I had to pass too many parameters to fit in a querystring.

So here’s the code i ended up using:

export function downloadFile(url: string, message: any, method: string, contentType ? : string, acceptContentType ? : string) {
 var xhr = new XMLHttpRequest();
 xhr.open(method, url);
 if (acceptContentType) {
  xhr.setRequestHeader('Accept', acceptContentType);
 }
 if (contentType) {
  xhr.setRequestHeader('content-type', contentType);
 }
 xhr.responseType = 'blob';
 xhr.onload = function() {
  if (this.status >= 400) {
   alert('error')
  } else {
   if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(xhr.response, 'afile.xlsx');
   } else {
    var objectUrl = URL.createObjectURL(xhr.response);
    window.location.href = objectUrl;
   }
  }
 };
 xhr.send(message);
}

I tried to do this via jquery.ajax but I couldn’t get it to work. So then I switched to using xmlhttprequest. This worked fine, though saving a file in javascript works differently in chrome / explorer.

8 comments:

  1. This content creates a new hope and inspiration with in me. Thanks for sharing article like this. The way you have stated everything above is quite awesome. Keep blogging like this.



    Dot Net Training Institute in Chennai

    ReplyDelete
  2. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing.
    Regards,
    SAP Training in Chennai with placement | java training in chennai with placement

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. I been working as a Web Designer for 5+ years, as a experienced guy this post also helps me to learn something new about the subject, Very well explanation and example. Thanks for it., Also I'm having a website for AngularJS Training which is one of the powerful tool.

    ReplyDelete
  5. To add onto that JavaScript is an object oriented language. However the way JavaScript handles objects and inheritance is a bit different from conventional object oriented programming languages like Java.
    web design lessons

    ReplyDelete
  6. Your Blog is really amazing with smart and interesting content.. Thanks for posting this wonderful post.It is very helpful to everyone..
    No.1 Embedded Project Center in Chennai | No.1 MatLab Project Center in Chennai | No.1 Application Project Center in Chennai

    ReplyDelete