php Base64编码上传的文件然后保存在数据库中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8559363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Base64 encode uploaded file then save in database
提问by John Kim
I want to base 64 encode uploaded file then save this into Blob type column of a table in MySQL database.
我想对上传的文件进行 base 64 编码,然后将其保存到 MySQL 数据库中表的 Blob 类型列中。
I have tried built in PHP function base64_encode with file variable but this does not seem to work.
我曾尝试使用文件变量内置 PHP 函数 base64_encode 但这似乎不起作用。
Is there a way we can do this?
有没有办法做到这一点?
The reason is that I do not want to use moveuploaded file into a folder.
原因是我不想使用 moveuploaded 文件到文件夹中。
Thank you.
谢谢你。
回答by DaveRandom
As @Sjoerd and @zerkms correctly point out, you do not need to do this - a blob column is be used to store raw binary data, so you can bypass the Base64 process and insert the raw data of the file.
正如@Sjoerd 和@zerkms 正确指出的那样,您不需要这样做 - 一个 blob 列用于存储原始二进制数据,因此您可以绕过 Base64 过程并插入文件的原始数据。
If you want to store images in a database (which, by the way, I personally don't like to do) it is better to store the raw data - Base64 encoding the data makes it larger, and means that it must be decoded before the image is rendered, which adds processing overhead.
如果您想将图像存储在数据库中(顺便说一下,我个人不喜欢这样做)最好存储原始数据 - Base64 编码数据使其更大,这意味着它必须在之前被解码图像被渲染,这增加了处理开销。
This is how you can insert the raw binary data (assuming the MySQL extension):
这是插入原始二进制数据的方法(假设是 MySQL 扩展):
$data = file_get_contents($_FILES['name_of_control']['tmp_name']);
$data = mysql_real_escape_string($data);
$query = "
INSERT INTO table
(`blob_column`)
VALUES
('$data')
";
mysql_query($query);
If you really do want to Base64 encode it (in which case it could just be stored in a varchar), just just add a base64_encode()
call:
如果你真的想对它进行 Base64 编码(在这种情况下它可以只存储在 varchar 中),只需添加一个base64_encode()
调用:
$data = file_get_contents($_FILES['name_of_control']['tmp_name']);
$data = base64_encode($data);
// There is an argument that this is unnecessary with base64 encoded data, but
// better safe than sorry :)
$data = mysql_real_escape_string($data);
$query = "
INSERT INTO table
(`varchar_column`)
VALUES
('$data')
";
mysql_query($query);