1

My case is to send a file to the backend but the only file content as byte array eg:

public saveFile(file: File, name: string, description: string): Observable<SymbolResponseEditModel> {

    let formData: FormData = new FormData();
    formData.append('FileName', name);
    formData.append('FileDescription', description);
    formData.append('Attachment', file); // <--- this must be a byte array instead of File 

    return this.http.post<SymbolResponseEditModel>(
        'http://senddata.com',
        formData
    );

Result of this code is that I send to the backend a file containing additional information at the begining a file containing additional information at the begining as you can see on the picture.

To do this I try to convert the file using file reader but I cannot convert a file to bytearray according to: Getting byte array through input type = file

var reader = new FileReader();
  reader.onload = function() {

    var arrayBuffer = this.result,
      array = new Uint8Array(arrayBuffer),
      binaryString = String.fromCharCode.apply(null, array);

    console.log(binaryString);

  }
  reader.readAsArrayBuffer(this.files[0]);

And the error

TS2345: Argument of type 'File' is not assignable to parameter of type 'ArrayBuffer | SharedArrayBuffer | ArrayLike<number>'.
      Type 'File' is missing the following properties from type 'SharedArrayBuffer': byteLength, length, [Symbol.species], [Symbol.toStringTag]

The second idea is to remove two lines from the file while downloading because the reasponse content type is octet-stream:

const reader = new FileReader();

reader.addEventListener('loadend', (e) => {
    const text = e.srcElement.result; // <-- this text is encoded but I don't want it. Anyway the file is different than I
     // sent and i am not able to read it. 
     let splittedString = text.split('\n');
     splittedString = splittedString.splice(2);
     let concatenedArray = splittedString.join('\n');
     this.fetch(concatenedArray, symbolName);
 });

 reader.readAsArrayBuffer(response);

This whould work but the reader encode the file.

Have you got any other idea how to send a file as byte array without additional information? Is it possible?

mlody
  • 11
  • 2

0 Answers0