I've been finding a way to insert an image to database via AJAX. Instead of submitting through form, I'd like to convert the image file into text (longblob), then send it to the PHP script via POST variable so I can access them via $_POST['var_name'] , then insert them normally through SQL, but the problem is, the Javascript FileReader couldn't return the valid image text AS IF you would normally obtain from the PHP side by using the fopen and fread funtions. I need to find a way to convert an image into text (longblob), so I can insert them into the table .
I tried using the FileReader
, then chose fileReader.readAsText
, but the result dosen't seems to be valid for type longblob in the database
// Here is in the JavaScript //
let image_file = document.getElementById("upload_image").files[0];
let vars = "image_data=";
let fileReader = new FileReader();
fileReader.onloadend = function()
{
// I pass in callback function, so I get this.result to assign else where
callBack(this.result);
}
fileReader.readAsText(image_file);
// Then, I concat the image text to the vars variable
vars += result;
/* By this time vars would be "image_data=#$@#$DGJ#J$@#!$#@$@$..."(some
converted string),but the problem is this image_data does not contain
the correct image string (when get from $_POST on the PHP side) . I
would like to know if there're any ways to get the correct image
string as if it's obtained by using fopen, then fread function on the
PHP side*/
Here is the correct image string from the PHP
����JFIF``��LEAD Technologies Inc. V1.01��� ��� }!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz�������������������������������������������������������������������������w!1AQaq"2�B���� #3R�br� $4�%�&'()56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������"0��?�ۭ D��V02��7��k����"��:���Kc�j��}������2c��8�j�#���9^W���B�l��C���Ո�LFW2�'�=G��Զ3���6��?�j��[b,(��%o;�&[p:����Ƭ��lM�c* �O� �n�6��df�Y�>8�t9�rNd��(��[����kxc��Ҹn۸\�Ү���;�1����^�N��%ux���.$%�Q�)�^�V.R�lI�'ʸ?....
The image file string after opened by using fopen and using fread functions. The real text that I echo out has 20000+ letters long, but on the JavaScipt FileReader, it gives me this..
����JFIF``��LEAD Technologies Inc. V1.01��� ��� }!1AQa"q2���#B��R��$3br� %
Yes, that's it! As you can see both results are pretty much the same. I'd love to know why I didn't get the same text to the PHP script from the JavaScript FileReader. Anyone know how to solve this? or maybe please give some suggestions on sending files via AJAX. Thanks a lot.