[英]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.