Angular 8 - send file as byte[] - file

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?

Related

How to edit text files with google apps script? It must be done with Drive Advanced Api [duplicate]

I want Google script variable data into Google drive as text file and update that text file regulatory via Google script!
The following code creates a text file and writes the data on it.I wonder how i can update the text file later ?
function createTextFile()
{
name="testFile.txt";
name2="testFolder";
var content = "this is text data to be written in text file";
var dir = DriveApp.getFoldersByName(name2).next()
var file = dir.createFile(name, content);
}
Just in case anyone's still interested 3 years later... :)
The following will create or append, assuming content is text:
function createOrAppendFile() {
var fileName="myfile";
var folderName="myfolder";
var content = "this is text data to be written in text file";
// get list of folders with matching name
var folderList = DriveApp.getFoldersByName(folderName);
if (folderList.hasNext()) {
// found matching folder
var folder = folderList.next();
// search for files with matching name
var fileList = folder.getFilesByName(fileName);
if (fileList.hasNext()) {
// found matching file - append text
var file = fileList.next();
var combinedContent = file.getBlob().getDataAsString() + content;
file.setContent(combinedContent);
}
else {
// file not found - create new
folder.createFile(fileName, content);
}
}
}
In summary, as there appears to be no append function, you instead simply read the existing file contents, add the new content, then (over)write the combined content back to the file.
*tip - add a "\n" between the old and new content for a new line separator
update Override the contents if the file is exists.
function saveData(folder, fileName, contents) {
var filename = "testFile.txt";
var children = folder.getFilesByName(filename);
var file = null;
if (children.hasNext()) {
file = children.next();
file.setContent(contents);
} else {
file = folder.createFile(filename, contents);
}
}
function test() {
var folders = DriveApp.getFoldersByName("testFolder");
if (folders.hasNext()) {
var folder = folders.next();
saveData(folder, "testfile.txt", "HelloWorld");
saveData(folder, "testfile.txt", "Welcome");
}
}

How to convert image file to base64 String in flutter?

I am try to convert a image file in flutter:
File _img=new File('/data/user/0/com.example.test3/app_flutter/2020-10-29T17:18:56.210347.png');
List<int> imageBytes = _img.readAsBytesSync();
String imageB64 = base64Encode(imageBytes);
print(imageB64);
But it look like is a wrong base64 String and I cannot decode to image on convert website:
https://codebeautify.org/base64-to-image-converter
iVBORw0KGgoAAAANSUhEUgAAAhwAAALECAYAAABDk+k+AAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAACAASURBVHic7d1ngFx1ucDhd9N77z0hbdMhCSAJVZoURS4C0psColcxFBXFKypKUywUQYp0EdtVQHpHTQLpZZOQnpDee9v7QeUSksxsyP7Ptuf5tnPeybwfCPvLmTNnIgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgNJRUFYvXFxcXFxWrw0AVVVBQUGZ/O6vVhYvCgBULYIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhMcAEByggMASE5wAADJCQ4AIDnBAQAkJzgAgOQEBwCQnOAAAJITHABAcoIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhMcAEByggMASE5wAADJCQ4AIDnBAQAkJzgAgOQEBwCQnOAAAJITHABAcoIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhMcAEByggMASE5wAADJCQ4AIDnBAQAkJzgAgOQEBwCQnOAAAJITHABAcoIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhMcAEByggMASE5wAADJCQ4AIDnBAQAkJzgAgOQEBwCQnOAAAJITHABAcoIDAEhOcAAAyQkOACA5wQEAJCc4AIDkBAcAkJzgAACSExwAQHKCAwBITnAAAMkJDgAgOcEBACQnOACA5AQHAJCc4AAAkhM
Is the dart base64 format is different to another?
Thanks.
You have to convert your bytes into an Uint8List object not a List<int>:
File _img = File(
'/data/user/0/com.example.test3/app_flutter/2020-10-29T17:18:56.210347.png');
final bytes = Uint8List.fromList(_img.readAsBytesSync());
final imgBase64 = base64Encode(bytes);
print(imgBase64);
I find that this case by the 'print' function cannot display fully base64 code.
If want to verify it, need to export to text file:
_write(String text) async {
final File file = File('/storage/emulated/0/xxx/my_file.txt');
await file.writeAsString(text);
print(file);
}

Read data from a wav file

I want to read a wav file sample rate and size from its header in Angular.
I am trying to use the Audio context to decode the data but I am unable to make it work.
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
audioCtx.decodeAudioData(uint8Array, function (buffer) {
//read data
})
I have an array of bytes but I get an error : parameter 1 is not of type ArrayBuffer.Then I convert it to ArrayBuffer but still get an error
Any ideas?

Getting path of audio file from sdcard

In my app I tried to pass the file path from one activity to another activity using intent.In my receiving activity I got the file path as "null".But when I print the file in first activity it prints the path.From my second activity I attach that file to mail using Gmailsender.This was the code I tried,
private void startRecord()
{
File file = new File(Environment.getExternalStorageDirectory(), "test.pcm");
try
{
file.createNewFile();
OutputStream outputStream = new FileOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
DataOutputStream dataOutputStream = new DataOutputStream(bufferedOutputStream);
int minBufferSize = AudioRecord.getMinBufferSize(8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
short[] audioData = new short[minBufferSize];
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
8000,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
minBufferSize);
audioRecord.startRecording();
while(recording)
{
int numberOfShort = audioRecord.read(audioData, 0, minBufferSize);
for(int i = 0; i < numberOfShort; i++)
{
dataOutputStream.writeShort(audioData[i]);
}
}
audioRecord.stop();
audioRecord.release();
dataOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
String audiofile;
audiofile=file.getAbsolutePath();
System.out.println("File Path::::"+audiofile);
}
Intent is,
Intent sigout=new Intent(getApplicationContext(),WeeklyendActivity.class);
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
startActivity(sigout);
In my receiving activity,
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
System.out.println("paathhhy frfom ::"+patty);
It prints null.Can anyone help me how to get the file path.And more thing I am not sure whether the audio would save in that file correctly?
Please anyone help me!!!Thanks in advance!
Based on your information that audioFile is a variable of type File, when you do this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile);
you are putting a File object in the extras Bundle. Then, when you try to get the extra from the Bundle you do this:
String patty=getIntent().getStringExtra("mnt/sdcard-text.pcm");
However, the object in this extra is of type File, not type String. This is why you are getting null.
If you only want to pass the name of the file, then put the extra like this:
sigout.putExtra("mnt/sdcard-test.pcm",audiofile.getAbsolutePath());

What is a compact way to save a float32array to disk on node.js?

JSON.stringify is obviously not space-efficient. What is the most elegant way to serialize and store a float32array using Node.js?
EDIT: People are closing the question for reasons such as being "opinion based" and "lack of an understanding of the problem". I seriously believe the first one was a missclick. For the second one, maybe this makes it more clear:
var fs = require("fs");
var len = 1000*1000*10;
var big_array = new Float32Array(len);
for (var i=0; i<len; ++i)
big_array[i] = Math.random();
// OBVIOUSLY NOT SPACE EFFICIENT \/
fs.writeFileSync("big_array.json",JSON.stringify(big_array));
It is not space efficient because you are representing numbers as strings, so an 8 bytes float will be using as much as ~20 utf8 chars, which is a waste. The question is: how to store the array in a space-efficient manner?
Finally I managed to write float32array to disk with nodejs and retrieve them on the browser, and I hope it will help you.
Write Float32Array to binary file in NodeJS
var fs = require('fs');
var wstream = fs.createWriteStream('data.dat');
var data = new Float32Array([1.1,2.2,3.3,4.4,5.5]);
//prepare the length of the buffer to 4 bytes per float
var buffer = new Buffer(data.length*4);
for(var i = 0; i < data.length; i++){
//write the float in Little-Endian and move the offset
buffer.writeFloatLE(data[i], i*4);
}
wstream.write(buffer);
wstream.end();
Read the file and convert it to a Float32Array on a Browser
var urlToFloatFile = 'data.dat';
var request = new XMLHttpRequest();
request.open('GET', urlToFloatFile, true);
//specify the response type as arraybuffer
request.responseType = 'arraybuffer';
request.onload = function (msg) {
var yourFloatData = new Float32Array(this.response);
console.log(yourFloatData);
};
request.send();
Thanks to #ben_a_adams from WebGL Dev List GGroup https://groups.google.com/forum/#!topic/webgl-dev-list/EbGUi_iSEx8 for the client side code
I've create a simple test to test roughly how much space a JSON serialization of a float array differs from a binary representation and the results are:
2.000.000 floating point values
7.8MB on a binary file
38.5MB on a JSON file
17.5 on a Gzipped JSON file
There is actually a much simpler version possible
let fs = require('fs')
let data = [150, 180]
fs.writeFileSync('mydata', new Buffer(new Uint32Array(data).buffer))
fs.readFile('mydata', (err, buf) => {
let restoredData = new Uint32Array(buf.buffer, buf.offset, buf.byteLength/4)
console.log(data[1])
console.log(restoredData[1])
});
Easy, clean way to do it:
const float32Array = new Float32Array([.69,.420])
const buffer = Buffer.from(float32Array.buffer)
fs.writeFileSync(filePath, buffer)
const loadedBuffer = fs.readFileSync(filePath)
const newFloat32Array = new Float32Array(loadedBuffer.buffer)
I believe you could use Meteor's EJSON:
http://docs.meteor.com/#ejson
https://npmjs.org/package/meteor-ejson
EJSON is an extension of JSON to support more types. It supports all
JSON-safe types, as well as:
Date (JavaScript Date)
Binary (JavaScript Uint8Array or the result of EJSON.newBinary)
User-defined types (see EJSON.addType. For example, Meteor.Collection.ObjectID is implemented this way.)

Resources