我正在嘗試使用 JS Blob() 函式下載檔案,但無法打開它。事先不清楚是什么型別,因為我有一個檔案串列,用戶可以選擇下載什么。Mac 說,格式可能已損壞,無法打開該檔案。
我擁有的 cURL 回應,我從中創建了一個 blob 是一個二進制字串(至少我相信是這樣,因為當我轉儲它時,您只會看到隨機符號和字符,就像使用文本編輯器打開影像時一樣)
這是我通過 cURL 的回應獲得的影像代碼
這是我下載此影像的代碼。
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();
已經為此苦苦掙扎了幾天,任何幫助表示贊賞。
此外,當我(在 Mac 終端中)執行以下命令時:
file test.jpeg
它回傳
test.jpeg: data
此致
編輯:我的 PHP 代碼
$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;
uj5u.com熱心網友回復:
您可以嘗試將影像資料序列化為base64字串并傳遞給客戶端
$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;
在這種情況下,在您的客戶端,您只需要像這樣放置 href 的回應文本:
const a = document.createElement('a');
a.href = response;
a.download = data.data.name;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/318452.html
標籤:javascript 查询 文件 下载 斑点
