douhan9748 2016-01-27 18:12
浏览 105

如何使用PHP检索/下载存储在MySQL数据库中的BLOB中的文件

The other day I recently wrote a program that takes a file that a user provided and inserts the actual file(driver) into a MySQL database BLOB. I did the insertion as follows:

$sql = "INSERT INTO Drivers (driver, filename, status, version, environments) VALUES(LOAD_FILE('$driver'), '$filename', $statusid, $driver_version, '$environments')";

As you can see above, the 'driver' field is the BLOB. I have the filename as well in a different field. So the question is, how can I easily get the BLOB and put it back into an actual file? I need to get this into a file so that I can upload it to a server via SCP. I've seen a few examples out there with content headers and such and they all look too complicated. It was easy to load with LOAD_FILE() and I didn't know if there was another simple option to get it back to an actual file? Sorry I don't have any code examples. I really don't know where to start.

  • 写回答

1条回答 默认 最新

  • dscrb00804 2016-12-26 17:37
    关注

    Your sql table should have at least two extra fields:

    `mime_type` varchar(255) NOT NULL,
    `size` int(10) unsigned NOT NULL,
    

    where:

    • mime_type is mime_content_type($path) and
    • size is the file's size in bytes, filesize($path)

    and PHP code should look like:

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: {$file['mime_type']}");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: {$file['size']}");
    header("Content-disposition: inline; filename= {$file['filename']}");
    
    return $file['driver'];
    

    The reasons for storing data as binary in SQL are dictated by business rules. For example, I store contracts that have to remain private.

    评论

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3