使用 Blob 将图像上传到 MySQL 数据库
首先澄清一下,我知道有更好的方法可以做到这一点,但我决心进行实验.
Just to first clarify, I know there are better ways to do this, but I'm determined to experiment.
基本上,我试图从表单帖子中获取图像,然后将其发送到数据库 MEDIUMBLOB 字段中.
Basically, I'm trying to grab an image from a form post, then send that into a database MEDIUMBLOB field.
不幸的是,使用我当前的方法,数据库列中的最终结果始终为零字节.
Unfortunately, using my current method, the end result in the database column is always zero bytes. phpMyAdmin Screenshot
这里是表单上传图片的代码:
Here is the code for the image upload on the form:
input type="file" name="_imagePost">
这是页面上的 PHP 代码,我使用的是 MySQLi :
Here is the PHP code on the page, I'm using MySQLi :
if(isset($_POST['_imagePost']))
{
$_useImagePost = 1;
$_imagePost = file_get_contents($_FILES['_imagePost']);
// Open DB Connection
$_conn = databaseConnect();
$_stmt = $_conn->prepare("INSERT INTO Question (Question_Type, Question_Text, Question_Answer, Question_UseImage, Question_Image) VALUES (?, ?, ?, ?, ?)");
$_stmt->bind_param("sssib", $_typePost, $_textPost, $_answerPost, $_useImagePost, $_null);
$_stmt->send_long_data(4,$_imagePost);
$_stmt->execute();
// Close DB Connection
$_conn->close();
}
我不确定的是,当输入类型为文件时,isset($_POST['_imagePost'])"是否有效.
What I am unsure of is if "isset($_POST['_imagePost'])" works when the input type is file.
然而,我可以肯定的是,当前的设置根本不起作用.
What I am sure of, however, is that the current setup doesn't work at all.
推荐答案
你写的:
$_imagePost = file_get_contents($_FILES['_imagePost']);
正确的语法是:
$_imagePost = file_get_contents($_FILES['_imagePost']['tmp_name']);
$_FILES
是一个带有以下键的关联数组:
$_FILES
is an associative array whit following keys:
- [name] => 原始文件名;
- [type] => 上传文件的 mimetype;
- [tmp_name] => 临时文件路径(上传文件的存储位置);
- [错误] => 错误;
- [size] => 上传文件的大小.
- 查看更多关于$_FILES
相关文章