0

I'm programming a webmail interface for educational purposes, and it has problems with attachments.

When testing with DevTools:

console.log( file )
file.length
new File( [ file ], "download.pdf" );

produces the following results:

> 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, …}

when I download the file "download.pdf" and verify these results on the server it matches the files (original and downloaded)

$ 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
$

When I compare the "download.pdf" files with "utf8.pdf" both files are the same!, which means the File() command encodes "file" string from iso8859-1 to utf-8

How can I prevent this from happening?

fwBasic
  • 154
  • 9

1 Answers1

0

Problem solved

Used "String" instead of "ArrayBuffer".

"String" is encoded to UTF-8 while "ArrayBuffer" remains intact !! ;))

here is a small program that converts a dataURL ("String") into "ArrayBuffer" and then put it on a "<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
}

fwBasic
  • 154
  • 9