I am receiving a Base64 encoded string that contains a word document (generated by thunderHead), that I decode with:
byte[] dataBytes = Convert.FromBase64String(data)
When I write directly this byteArray into a file:
File.WriteAllBytes("myFile.doc", dataByte);
The word document is properly written (é, è are shown properly), but it's not the case when I send this byteArray to the front (angularjs):
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(dataByte);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/msword");(also tried "application/octet-stream")
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachement");
response.Content.Headers.ContentDisposition.Filename = "toto.doc"
return response;
I can't figure it out....some help would be appreciated thanks!
Solved my problem, as #peco pointed, the problem was on the front part, I was doin a $http.post(url, data).then ... and missed to add {responseType: 'arrayBuffer'} as a third parameter: $http.post(url, data, {responseType: 'arrayBuffer'}).then... Thanks.
Related
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);
}
I'm trying to length prefix a payload that i'm streaming through a socket, and so far the only way i've been able to get it working is:
Uint8List payload = getPayloadSomehow();
final lBytes = ByteData(4)..setUint32(0, payload.length);
final prefix = lBytes.buffer.asUint8List();
final prefixedPayload = []..addAll(prefix)..addAll(payload);
Creating a ByteData and filling it with the length, and then extracting the buffer as a Uint8List feels very roundabout. But i haven't been able to find a cleaner way to do the conversion and prefixing.
I'd really appreciate it if someone could point me to a better solution, thanks.
How about:
var payload = getPayloadSomehow();
var prefixed = Uint8List(payload.length + 4);
prefixed.buffer.asUint32List(0, 1)[0] = payload.length;
prefixed.setRange(4, prefixed.length, payload);
I am using App Engine application to receive emails to a specific list of email address ending with #my-app-id.appspotmail.com will be sent to your application.
Multipart multiPart = (Multipart) message.getContent();
BodyPart bp = multiPart.getBodyPart(0);
log.info("count is "+multiPart.getCount());
String attachFiles = "";
String messageContent = "";
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
String fileName = part.getFileName();
log.info("file name is "+fileName);
} else {
// this part may be the message content
messageContent = part.getContent().toString();
}
}
I want to store the File inside a Blob store but i did not find an API for it, It is going inside the IF loop and am able to get the attachment file name. Any help will be appreciated.
You can read all the data inside the attachment part using the MimeBodyPart.getInputStream method, but you'll need to read the data yourself and create the Blob.
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.)
I'm trying to get file content from 'upload success' handler in GAE. File is uploaded to the url:
blobstoreService.createUploadUrl("/onupload", uploadOptions));
So, in /onupload, I'm doing like:
BlobKey myFile = context.getRequestBlobs().get("myFile").get(0);
and then I've tried:
InputStream is = new BlobstoreInputStream(myFile);
// .. read the stream
which failed with com.google.appengine.api.blobstore.BlobstoreInputStream$BlobstoreIOException: BlobstoreInputStream received an invalid blob key: =?ISO-8859-1?Q?AMIfv96J=2DsyIbhm5=5FET?=
and
FileReadChannel ch = fileService.openReadChannel(myFile, false);
which failed with
java.io.IOException
at com.google.appengine.api.files.FileServiceImpl.translateException(FileServiceImpl.java:615)
at com.google.appengine.api.files.FileServiceImpl.makeSyncCall(FileServiceImpl.java:588)
at com.google.appengine.api.files.FileServiceImpl.open(FileServiceImpl.java:521)
at com.google.appengine.api.files.FileServiceImpl.openForRead(FileServiceImpl.java:481)
at com.google.appengine.api.files.FileServiceImpl.openForRead(FileServiceImpl.java:473)
at com.google.appengine.api.files.FileServiceImpl.openReadChannel(FileServiceImpl.java:197)
Any thoughts on what am I doing wrong and is it possible at all to read file's content in upload hander?
Note, that for blobstore fs (not GS) it was working fine.
I think you are trying to read a file from the google cloud storage.
Have you seen the example [1] on the docs?
Particularly this part:
/ At this point, the file is visible in App Engine as:
// "/gs/BUCKETNAME/FILENAME"
// and to anybody on the Internet through Cloud Storage as:
// (http://storage.googleapis.com/BUCKETNAME/FILENAME)
// We can now read the file through the API:
String filename = "/gs/" + BUCKETNAME + "/" + FILENAME;
AppEngineFile readableFile = new AppEngineFile(filename);
FileReadChannel readChannel =
fileService.openReadChannel(readableFile, false);
// Again, different standard Java ways of reading from the channel.
BufferedReader reader =
new BufferedReader(Channels.newReader(readChannel, "UTF8"));
String line = reader.readLine();
resp.getWriter().println("READ:" + line);
// line = "The woods are lovely, dark, and deep."
readChannel.close();
[1] https://developers.google.com/appengine/docs/java/googlestorage/overview#Complete_Sample_App