【问题标题】:Can't store a .pdf file in a blob in mySQL无法将 .pdf 文件存储在 mySQL 的 blob 中
【发布时间】:2014-07-31 14:35:41
【问题描述】:

所以我正在尝试将 PDF 文件上传到 mySQL blob,表行被插入,但在作为 mediumBlob 类型的 fileContent 中,它始终显示为 [BLOB 0 B] 并且在下载文件时,它被下载0字节。我回显了 $content,它显示了 pdf 文件的特殊字符。

$erro = '';
$tipo = '';
if (isset($_POST['submit']) && isset($_POST['text']) && $_POST['text'] !== null && isset($_POST['userID']))
    {
        if(preg_match('/^[a-z0-9-]+$/',$_POST['text']) && strlen($_POST['text']) < 15 ) 
        {

            if (substr($_FILES['file']['name'], -3, 3) == "pdf" && $_FILES["file"]["size"] < 1000000) 
            {

              if ($_FILES["file"]["error"] > 0) 
              {
                $erro = "Problema: " . $_FILES["file"]["error"];
                $tipo = 'erro';
              } 
              else 
              {
                  $_FILES["file"]["name"] = $_POST['text'].'.pdf';
                  $erro = "Ficheiro guardado com sucesso.";
                  $tipo = 'sucesso';
               }
            }
            else 
            {
               $erro = "Apenas .PDF com menos de 10 Mb são permitidos!";
               $tipo = 'erro';
            }
        } 
        else
        {
            $erro = "Nome inválido";
            $tipo = 'erro';
        }

        if ($tipo == 'sucesso')
        {
            $content = $db->real_escape_string(file_get_contents($_FILES['file']['tmp_name']));

            if ($_FILES["file"]["size"] > 0)
            {
                $smt = $db->prepare('INSERT into uploads (userRefID,fileName,fileType,fileSize,fileContent,uploadDate) values(?,?,?,?,?,?)');
                $smt->bind_param('issibs', $_POST['userID'], $_FILES["file"]["name"], $_FILES["file"]["type"], $_FILES["file"]["size"], $content ,date(c));
                $smt->execute();
                $smt->close();
            }
        }



    }

我做错了什么?

【问题讨论】:

  • 这个 blob 中大约有多少字节?
  • MySQL 设置max_allowed_packet 将对此有发言权。默认情况下,它设置为 16MB,因此这是您的最大查询长度。
  • 我上传的文件有 131Kb。怎么长度比那个长?
  • 不是问题的根本原因,但我认为您在传递内容之前不需要 real_escape_string,因为您正在使用 bind_param 为您处理此问题。
  • 我试过没有它,结果相同。现在我测试了一个 3Kb 的 PDF,结果相同....

标签: php mysql blob


【解决方案1】:

根据this comment,您不应直接在bind_param 中传递blob,而应使用send_long_data

来自send_long_data 的文档是一个示例:

$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
    $stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();

【讨论】:

  • 我现在尝试使用它。我得到相同的结果 [BLOB 0 B]
  • send_long_data的第一个参数是SQL语句中的参数号。所以这里应该是 4,而不是 0。
猜你喜欢
  • 2011-06-16
  • 2010-11-02
  • 2019-12-26
  • 1970-01-01
  • 2021-06-17
  • 2019-11-21
  • 2019-04-04
  • 1970-01-01
  • 2023-03-03
相关资源
最近更新 更多