一些一般背景:這是一個使用 MERN 堆疊的應用程式,但問題更具體地針對 AWS S3 資料。
我設定了 S3,并將我的應用程式中的影像和檔案存盤在那里。我通常用服務器生成signedURLs,然后從瀏覽器直接上傳。
在我的應用程式資料庫中,我將物件 URI 存盤為字串,然后存盤一個影像,例如我可以用<img/>標簽渲染沒問題。到現在為止還挺好。
但是,當它們是 PDF 并且我想讓用戶下載我存盤在 S3 中的 PDF 時,這樣做<a href={s3Uri} download>只會導致 pdf 在另一個視窗/選項卡中打開,而不是提示用戶下載。我相信這是由于下載屬性依賴于同源并且您無法從外部資源下載檔案(如果我錯了,請糾正我)
那么我的下一個嘗試是直接使用 axios 對資源進行 http 獲取,它看起來像這樣
axios.create({
baseURL: attachment.fileUrl,
headers: {common: {Authorization: ''}}
})
.get('')
.then(res => {
console.log(res)
console.log(typeof res.data)
console.log(new Buffer.from(res.data).toString())
})
因此,通過這樣做,我成功讀取了回應標頭(有用,因為我可以以不同的方式處理影像/檔案)但是當我嘗試讀取回傳的二進制資料時,我沒有成功決議它甚至確定它是如何編碼的,它看起來像這樣
%PDF-1.3
3 0 obj
<</Type /Page
/Parent 1 0 R
/Resources 2 0 R
/Contents 4 0 R>>
endobj
4 0 obj
<</Filter /FlateDecode /Length 1811>>
stream
x?X?R?=k=E????????Na???/???? ?[?]??.?,??^ ?wF0?.??Ie?0?o???O_IoG????p??4?BJI???g??d|??H?$?12(R*oB??:%??????:?R?Ф6?X??[:?[??h?(?MQ???>???;l[[??VN?hK/][?!?mJC
.... and so on
我有另一個功能,用于允許用戶下載我作為 base64 中的字串直接存盤在我的資料庫中的 PDF。這些是我的應用程式生成的 PDF 檔案并且相當小,所以我將它們直接存盤在資料庫中,而不是我存盤在 AWS S3 中的那些是用戶提交的并且大小可能為幾 MB(我的資料庫中的那些只是一個幾KB)
我用來處理我的 base64 pdf 并為用戶提供可下載鏈接的函式如下所示
export const makePdfUrlFromBase64 = (base64) => {
const binaryImg = atob(base64);
const binaryImgLength = binaryImg.length;
const arrayBuffer = new ArrayBuffer(binaryImgLength);
const uInt8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < binaryImgLength; i ) {
uInt8Array[i] = binaryImg.charCodeAt(i);
}
const outputBlob = new Blob([uInt8Array], {type: 'application/pdf'});
return URL.createObjectURL(outputBlob)
}
但是,當我嘗試將此函式應用于從 AWS 回傳的資料時,出現此錯誤:
DOMException: Failed to execute 'atob' on 'Window': The string to be decoded contains characters outside of the Latin1 range.
那么我從 AWS 那里獲得了什么樣的二進制資料編碼?
注意:我可以通過像這樣在 img 標簽中傳遞 src 來用這個二進制資料渲染影像:
<img src={data:${res.headers['Content-Type']};base64,${res.data}} />
這是我最大的暗示,這是某種形式的 base64?
PLEASE! If anyone has a clue how i can achieve my goal here, im all ears! The goal is to be able to prompt the user to download the resource which i have in an S3 URI. I can link to it and they can open it in browser, and then download manually, but i want to force the prompt.
Anybody know what kind of data is being returned here? any way to parse it as a stream? a buffer?
I have tried to stringify it with JSON or to log it to the console as a string, im open to all suggestions at this point
uj5u.com熱心網友回復:
您正在執行各種不需要的轉換。當您執行GET請求時,您已經擁有所需格式的資料。
const response = await fetch(attachment.fileUrl,
headers: {Authorization: ''}}
});
const blob = await response.blob();
return URL.createObjectURL(res.data);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/341216.html
