how to download blob based file from MySQL database in PHP?

ぐ巨炮叔叔 提交于 2019-11-28 10:32:05
Sampath

This is the most common problem faced while dealing with the blob file. From your example, I can see that you are saving "fileType" as the extensions of the files (i.e 'jpg' for images, 'pdf' for pdf files etc.), you are uploading. But instead of that you can can save file type as the MIME content type.

Suppose if you upload a jpeg image - the MIME type will be stored in the "fileType" as the "image/jpeg". Similarly for pdf it will be stored as "application/pdf". I designed code like this to download the blob file from the database. I am going to assume that the files are already uploaded into the database table you created.

Database table "uploads"

| fileID | fileName | fileType | fileSize |fileData | userID |

download.php

<?php
$connection =  mysqli_connect("localhost","root"," ",your_database)
               or die('Database Connection Failed');
mysqli_set_charset($connection,'utf-8');

$id = 1;

// Use a prepared statement in production to avoid SQL injection;
// we can get away with this here because we're the only ones who
// are going to use this script.
$query = "SELECT * " ."FROM uploads WHERE userID = '$id'";
$result = mysqli_query($connection,$query) 
       or die('Error, query failed');
list($id, $file, $type, $size,$content) = mysqli_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$file");
ob_clean();
flush();
echo $content;
mysqli_close($connection);
exit;

?>

You can find the complete code of blob-upload here.

you can use session and post filename and file content to download page

session_start();
$_SESSION['filename'] = $filename
$_SESSION['file'] = $file
<a href="download.php">echo "Download File"</a>

and in download.php use this code

session_start();
$filename = $_SESSION['filename'];
$file = $_SESSION['file'];
header("Content-Disposition: attachment; filename=$filename");
ob_clean();
flush();
echo $file;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!