0
Problem:
I am trying to pass to the database a String containing the bytes of an image that was externally loaded to place in a BLOB field. As always, the bytes of the image have single quotes '
, double quotes "
and backslash \
. Turns out the backslash is a metacharacter and the quotes are delimiters of a literal string, and that’s where the problems arise. See the example bytes:
"Íäwóužü'vaõyt¾’m&²2\
When loading these bytes into String, I need them to stay "escapades", thus:
\"Íäwóužü'vaõyt¾ ’m&²2\\
If I try to carry them inside the object ByteArray
of Flash, bytes are recognized normally, but for communication with the database, it is necessary that they are in the format of String
.
Below an example in the code:
var loader:Loader = new Loader();
loader.load(new URLRequest("URL_DA_IMAGEM"));
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void {
var string:String = loader.content.loaderInfo.bytes.toString();
var query:String = "INSERT INTO tabela (arquivo) VALUES (' "+string+" ')";
var bytearray:ByteArray = loader.content.loaderInfo.bytes;
trace(loader.content.loaderInfo.bytes); //"ÍäWÓužü’vaŽyt¾'m&²2\ - VALOR CORRETO, PORÉM NÃO ESCAPADOS
trace(string); //"ÍäWÓužü’vaŽyt¾'m&²2\ - VALOR CORRETO, PORÉM NÃO ESCAPADOS
trace(query); /*Erro pois a string com as aspas simples/aspas duplas não está escapada,
logo a query dá erro de syntax: INSERT INTO tabela (arquivo) VALUES (' "ÍäWÓužü’vaŽyt¾'m&²2\ ')
*/
}
Attempts:
- Use String
query
passing as parameter theByteArray
. But I got error, because Bytearray is notString
. - Method
replace
with Regexp does not work:string.replace(/(\')/g, "\'");
because Flash automatically removes the backslash, and does not keep it.
Question:
Someone has a solution?
Unfortunately the connection is with Mysql and not SQL Local and I am using Flash Player, so the Adobe AIR classes are incompatible.
– bio
Got it. There is no Mysql connection utility available that accepts parameterized SQL?
– Andre
I don’t think so. Actionscript itself doesn’t have an internal class for Mysql connections. The library I’m using is ASQL, an old and discontinued but functional library. I tried using the same Flash object (Sqlstatement), but I can’t pass parameters through it.
– bio
The problem is, you cannot take any external data and save it in your database without treatment. Your application is subject to SQL injection. Imagine someone uploads a file containing the bytes
39 41 59 32 68 82 79 80 32 84 65 66 76 69 32 70 73 76 69 83
. By doing toString, it turns'); DROP TABLE FILES
.– Andre
What you can try to do is convert each byte to int, then to string. It will have a representation similar to the one above. And protects you from SQL injection...
– Andre
Got it, the coding for BASE64 helped me too, that would be an alternative?
– bio
I believe it is safe. Base64 accepts only characters
[a-zA-Z0-9+/]
.– Andre