I am trying to download a File using the JS Blob() function, but i cannot open it. It is not clear what type beforehand as I got a filelist, the user can choose what to download. Mac says, that the format might be damaged and that it cannot open that file.
The cURL response I have, from which i create a blob is a binary string (at least i believe so because when i dump it, you see only random symbols and characters, as when you open an image with the text editor)
Here is the Image code as I have it via response from my cURL
and here is my code to download this Image.
var a;
a = document.createElement('a');
a.href = URL.createObjectURL(new Blob([JSON.stringify(response)]));
// here i tried with and without JSON.stringify
// also tried new Blob([JSON.stringify(response)],{type:'image/jpeg'}) or with * instead of jpeg, nothing works. Does anybody happen to know what mistake i am doing?
a.download = data.data.name;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
Been struggling with this for a few days now, any help is appreciated.
Also when i (in Mac Terminal) do the following command :
file test.jpeg
it returns
test.jpeg: data
Best Regards
EDIT: My PHP Code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://myapi.com/webapp/api/v1/document/id/" . $id . "/download");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('AuthenticationToken:' . $token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
CodePudding user response:
You can try to serialize the image data to base64 string and pass it to the client
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://myapi.com/webapp/api/v1/document/id/" . $id . "/download");
curl_setopt($ch, CURLOPT_HTTPHEADER, array("AuthenticationToken:" . $token));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);
$base64 = "data:/" . $contentType . ";base64," . base64_encode($output);
echo $base64;
It this case, on your client side you just need to put the response text for the href like this:
const a = document.createElement('a');
a.href = response;
a.download = data.data.name;
a.style.display = 'none';
document.body.appendChild(a);
a.click();