FileSaver.js is saving corrupt images
Asked Answered
L

2

6

This was working fine and suddenly stopped working. I'm not sure what exactly changed.

I need to download multiple images via URLs.

I'm using the following code:
https://plnkr.co/edit/nsxgwmNYUAVBRaXgDYys?p=preview

$http({
  method:"GET",
  url:"imageurl"
}).then(function(response){

  saveAs(new Blob([response.data]), "image.jpg");

},function(err){

});

The files have different sizes, they are not 0 bytes.

Looney answered 8/11, 2017 at 9:3 Comment(0)
H
4

For others coming here, check this solution.

What needed to be done was to add responseType: "blob" to the request:

$http({
  method:"GET",
  url:"imageurl",
  responseType: "blob"
})
.then(...)

Here is the documentation for the responseType valid values, where it says the default is "" so the response is treated as text:

"": An empty responseType string is treated the same as "text", the default type (therefore, as a DOMString).

"blob:": The response is a Blob object containing the binary data.

Harhay answered 20/6, 2018 at 21:49 Comment(0)
A
0

Following code worked for me:

axios.get(`http://localhost:61078/api/values`, {
  responseType: 'blob',
}).then(response => {
  if (response) {
    var FileSaver = require('file-saver');
    FileSaver.saveAs(new Blob([response.data]), "image.png");
  }
});
Acro answered 3/9, 2018 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.