11

I have webApi return me a blob file that I have to display. how can I know what type is the blob that I got? It could be anything, pdf, doc, jpeg etc.

$http({ method: 'GET', url: (itemsUrl), responseType: 'arraybuffer' }).then(function mySucces(res) {
    var byteArray = res.data;
    byteArray = new Uint8Array(byteArray);
    var file = new Blob([byteArray], { type: '??????' });
    var fileURL = URL.createObjectURL(file);
    window.open(fileURL);
});

or, how can I open blob in a new window without know the file type?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
rikush
  • 520
  • 1
  • 6
  • 20

1 Answers1

27

Use response.headers() to get the content type:

var config = { responseType: 'blob' };

$http.get(itemsUrl, config).then(function onSuccess(response) {
    var blob = response.data;
    var contentType = response.headers("content-type");
    var fileURL = URL.createObjectURL(blob);
    window.open(fileURL); 
});

Consider using 'blob' as the responseType.

For more information, see MDN XHR responseType.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • 1
    Just for a quick reference if anyone wants to know how to get blob response when using `POST`: `$http.post(url, data, config)`. (See https://code.angularjs.org/1.6.10/docs/api/ng/service/$http#post ) – Qi Fan Aug 15 '18 at 17:51
  • 2
    you are not using your contentType variable, so why did you create it? – sports Nov 28 '18 at 18:15
  • 1
    The title of the question says "get blob and extract type from response". – georgeawg Nov 28 '18 at 18:25