[英]problem encoding / decoding base64 data to String to File()
我正在為教育目的編寫網絡郵件界面,但附件有問題。
使用DevTools進行測試時:
console.log( file )
file.length
new File( [ file ], "download.pdf" );
產生以下結果:
> console.log( file )
< ...
< ...
< Ò:ašSéàƒ‰òâ#ZMÖ…S©øz‡cß¾}uµ4ƒX™:´ìø,^j<¤Ö#AŒŽtaù£´tc¬¾t"
< Show more (26.7 kB) Copy
> file.length
< 18899
> new File( [ file ], "download.pdf", )
< File {name: "test.pdf", lastModified: 1596733568533, lastModifiedDate: Thu Aug 06 2020 13:06:08 GMT-0400 (hora de Venezuela)
, webkitRelativePath: "", size: 26739, …}
當我下載文件“download.pdf”並在服務器上驗證這些結果時,它與文件匹配(原始文件和下載文件)
$ ls -go *pdf
-rw-rw-r-- 1 26739 ago 6 09:58 download.pdf
-rw-rw-r-- 1 18899 ago 3 20:41 file.pdf
$ file *pdf
download.pdf: PDF document, version 1.5
file.pdf: PDF document, version 1.5
$ iconv -f iso8859-1 -t utf-8 <file.pdf>utf8.pdf
$ ls -go *pdf
-rw-rw-r-- 1 26739 ago 6 09:58 download.pdf
-rw-rw-r-- 1 18899 ago 3 20:41 file.pdf
-rw-rw-r-- 1 26739 ago 6 14:18 utf8.pdf
$ cmp download.pdf utf8.pdf
$
當我將“download.pdf”文件與“utf8.pdf”進行比較時,這兩個文件是相同的,這意味着 File() 命令將“file”字符串從 iso8859-1 編碼為 utf-8
我怎樣才能防止這種情況發生?
使用“ String ”而不是“ ArrayBuffer ”。
“ String ”被編碼為 UTF-8 而“ ArrayBuffer ”保持不變;! ;))
下面是一個小程序,將一個dataURL(“ String ”)轉換成“ ArrayBuffer ”,然后放到一個“ <input type”file"> ”中:
function Set_Attachment( dataURL, fileName ) {
var files = [];
var string = atob( dataURL.split("base64,")[1]||"" );
var fileType = (dataURL.split(":")[1]||"").split(";")[0];
// Convert String into ArrayBuffer:
for ( var Bits = [], i = 0; i < string.length; i++ ) {
Bits.push(string.charCodeAt(i));
}
arrayBuffer = new Uint8Array(Bits).buffer;
// End of Convert
files.push( new File([arrayBuffer], fileName, {"type":fileType}));
var inputFile = document.createElement("input");
inputFile.name = "attachment";
inputFile.id = "fileDownload";
inputFile.type = "file";
inputFile.files = new FileListItem(files);
return inputFile;
}
// taken from stackoverflow
// https://stackoverflow.com/questions/52078853/is-it-possible-to-update-filelist
function FileListItem(a) {
a = [].slice.call(Array.isArray(a) ? a : arguments)
for (var c, b = c = a.length, d = !0; b-- && d;) d = a[b] instanceof File
if (!d) throw new TypeError("expected argument to FileList is File or array of File objects")
for (b = (new ClipboardEvent("")).clipboardData || new DataTransfer; c--;) b.items.add(a[c])
return b.files
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.