Attach image and send it via json in base64 encoding
Updating the answer based on comment. you can refer to the example on sandbox
Please add create a promise to avoid callback hell. Here I have promised the base46 Function. Promisification
const getBase64Promise = function (file) {
return new Promise((resolve, reject) => {
getBase64(file, (success,err) => {
if(err) reject(err)
else resolve(success);
});
});
};
Like this
async function construct_json(form, callback) {
let data = await getBase64Promise(form.get("picture"));
let json = {
picture: data
};
return json;
}
Node JS, How to properly store Base64 String in JSON string?
Your approach is good, Base64 strings cannot have backslashes in them, and the rest will be escaped.
Base64 index Table :
0 A 16 Q 32 g 48 w
1 B 17 R 33 h 49 x
2 C 18 S 34 i 50 y
3 D 19 T 35 j 51 z
4 E 20 U 36 k 52 0
5 F 21 V 37 l 53 1
6 G 22 W 38 m 54 2
7 H 23 X 39 n 55 3
8 I 24 Y 40 o 56 4
9 J 25 Z 41 p 57 5
10 K 26 a 42 q 58 6
11 L 27 b 43 r 59 7
12 M 28 c 44 s 60 8
13 N 29 d 45 t 61 9
14 O 30 e 46 u 62 +
15 P 31 f 47 v 63 /
and with the given string, it works perfectly :
a={"password":"123456",key:"MIIIhQIBAzCCCD8GCSqGSIb3DQEHAaCCCDAEgggsMIAwgAYJKoZIhvcNAQcBoIAEggEOMIIBCjCCAQYGCyqGSIb3DQEMCgECoG4wbDAoBgoqhkiG9w0BDAEDMBoEFOWB9Rf4cT/NBObHUQW6sCOtB2AbAgIEAARAfTkFJwD66tZ2p30iXGLNtyH41D4RlWSof/MJ3w91rU22sQmCZkRR7UzgOlaoFWggWB2a2FHYOMpNjRbm+d9+hjGBhjAjBgkqhkiG9w0BCRUxFgQU5W/loImfeHgVra9dJW2noKcMLBMwXwYJKoZIhvcNAQkUMVIeUABlADUANgBmAGUANQBhADAAOAA5ADkAZgA3ADgANwA4ADEANQBhAGQAYQBmADUAZAAyADUANgBkAGEANwBhADAAYQA3ADAAYwAyAGMAMQAzAAAAADCABgkqhkiG9w0BBwaggDCAAgEAMIAGCSqGSIb3DQEHATAoBgoqhkiG9w0BDAEGMBoE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Vz1u8nuXB+xKvTnVNl7MfJtxLuEe6IC0jttX2QwbtlSHTYKHA1+4lKe9SKbtWV1VIhgA+P/xXrk8h4E10RyRi3eSdgtMaM1RAYaUADQmA1Dh5OlTtPc1JOGnMHsaBRDKYggiMBENJp6JyoU9RgS6tkhFZP0BZkCLf7t0janQSOP5gTDT2wAhgAAAAAAAAAAAAAAADA9MCEwCQYFKw4DAhoFAAQUwl/G8qYgHK0C2n1jqLTQjEjqkvkEFLPjN/qfoSjcIzyT35GhE0SgivRyAgIEAA=="}
Looking at your screencap, it looks like you have a newline in your String, could that be the case? I'm at a loss here : http://prnt.sc/ddyq6y
Convert base64 string to JSON .NET
You have a base-64 string, and you seem to what a deserialized object; so you'll need multiple steps:
- decode the base-64 to binary
- interpret the binary as text
- define an object model that matches the expected data
- deserialize the text as the object model
For example:
static void Main()
{
var base64 = @"e0tleSA6ICdhYmMnLCBpc0V4aXN0czogJ3RydWUnfQ==";
var blob = Convert.FromBase64String(base64);
var json = Encoding.UTF8.GetString(blob);
// string: "{Key : 'abc', isExists: 'true'}"
var obj = JsonConvert.DeserializeObject<MyPayload>(json);
Console.WriteLine(obj.Key);
Console.WriteLine(obj.IsExists);
}
class MyPayload
{
public bool IsExists { get; set; }
public string Key { get; set; }
}
Base64 encode a javascript object
You misunderstood the Buffer(str, [encoding])
constructor, the encoding
tells the constructor what encoding was used to create str
, or what encoding the constructor should use to decode str
into a byte array.
Basically the Buffer
class represents byte streams, it's only when you convert it from/to strings that encoding comes into context.
You should instead use buffer.toString("base64")
to get base-64 encoded of the buffer content.
let objJsonStr = JSON.stringify(obj);
let objJsonB64 = Buffer.from(objJsonStr).toString("base64");
Serialize in JSON a base64 encoded data
You must be careful about the datatypes.
If you read a binary image, you get bytes.
If you encode these bytes in base64, you get ... bytes again! (see documentation on b64encode)
json can't handle raw bytes, that's why you get the error.
I have just written some example, with comments, I hope it helps:
from base64 import b64encode
from json import dumps
ENCODING = 'utf-8'
IMAGE_NAME = 'spam.jpg'
JSON_NAME = 'output.json'
# first: reading the binary stuff
# note the 'rb' flag
# result: bytes
with open(IMAGE_NAME, 'rb') as open_file:
byte_content = open_file.read()
# second: base64 encode read data
# result: bytes (again)
base64_bytes = b64encode(byte_content)
# third: decode these bytes to text
# result: string (in utf-8)
base64_string = base64_bytes.decode(ENCODING)
# optional: doing stuff with the data
# result here: some dict
raw_data = {IMAGE_NAME: base64_string}
# now: encoding the data to json
# result: string
json_data = dumps(raw_data, indent=2)
# finally: writing the json string to disk
# note the 'w' flag, no 'b' needed as we deal with text here
with open(JSON_NAME, 'w') as another_open_file:
another_open_file.write(json_data)
Send Base64 with JSONObject to server(ANDROID)
Do this in your PHP file
- Make a Json String from posted data (base64), and remove "\n" character (to avoid that character)
- Decode that JSON String to remove that JSON Character
- Get the decoded string
This is work for me
$img_base64 = $_POST['ArchivoTexto'];
$sdata = '{"val" : "'.sub_str("\n","",$img_base64).'"}';
$ddata = json_decode($sdata);
$jdata = $ddata->val;//$jdata contain the clear base64 String
Related Topics
How to Detect Browser Back Button Click Event Using Angular
Automatically Force Mobile Browser to Desktop View
Get Directory of a File Name in JavaScript
How to Open a File/Browse Dialog Using JavaScript
Easiest Way to Open a Download Window Without Navigating Away from the Page
How to Check a Radio Button in the Table Row Based on That Column Header
How to Reload the Page Without the Query Parameters
How to Select All Textframes in Document, and Retrieve the Text in Adobe Indesign
Angularjs:Ng-Model Binding Not Updating When Changed With Jquery
Foreach Is Not a Function Error With JavaScript Array
Remove Whitespace Inside Json Object Key Value Pair
How to Loop Through Json Array and Get Specific Values
Show Virtual Keyboard on Mobile Phones in JavaScript
How to Replace Double/Multiple Slash to Single in Url
Hiding the Address Bar of a Browser (Popup)
How to Manage Hide and Show Multiple Div and Sections Using Jquery
Image Resizing Client-Side With JavaScript Before Upload to the Server