从数据库Blob类型字段下载文档文件的实现方案咨询(附PHP上传代码)
Hey there! Looking at your upload code, I notice you're storing the document as a base64-encoded string in your file_name field (instead of a raw BLOB). That's totally fine—here's a straightforward way to implement the download functionality to retrieve that file:
Step-by-Step Implementation
First, let's break down what we need to do: pull the encoded data from the database, decode it back to raw file bytes, then send the right HTTP headers to trigger a browser download.
Here's a complete code example (I'll assume you're using a file ID to fetch the record—adjust this if you use a different unique identifier like the filename):
// Get the file identifier from the request (e.g., via a GET parameter) $fileId = $_GET['id'] ?? null; if (!$fileId) { die("Please specify a file to download."); } try { // Connect to your database (same credentials as your upload code) $pdo = new PDO("mysql:host=localhost;dbname=db", "root", "Password"); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Fetch the encoded file content and original filename $stmt = $pdo->prepare("SELECT file_name, C_name FROM upload_file WHERE id = ?"); $stmt->bindParam(1, $fileId, PDO::PARAM_INT); $stmt->execute(); $fileRecord = $stmt->fetch(PDO::FETCH_ASSOC); if (!$fileRecord) { die("File not found in database."); } // Decode the base64 string back to raw file data $rawFile = base64_decode($fileRecord['file_name']); if ($rawFile === false) { die("Failed to decode the file content."); } // Set HTTP headers to trigger download $fileName = $fileRecord['C_name']; // Auto-detect MIME type (or hardcode it if you only handle Word docs) $mimeType = mime_content_type($fileName) ?: "application/octet-stream"; header("Content-Type: {$mimeType}"); header("Content-Disposition: attachment; filename=\"" . htmlspecialchars($fileName) . "\""); header("Content-Length: " . strlen($rawFile)); header("Cache-Control: no-cache"); // Output the file content echo $rawFile; exit; // Stop execution to avoid extra output messing up the file } catch (PDOException $e) { die("Database error: " . $e->getMessage()); } catch (Exception $e) { die("Download failed: " . $e->getMessage()); }
Key Notes to Keep in Mind
- Why decode? Since you used
base64_encodewhen uploading, we needbase64_decodeto get back the original file bytes—skip this step only if you stored raw BLOB data (which your code doesn't do). - Safe filenames: Using
htmlspecialchars($fileName)prevents issues with special characters in the filename that might break the HTTP header. - MIME Types: If you only handle Word 2007 files, you can hardcode the MIME type to
application/vnd.openxmlformats-officedocument.wordprocessingml.documentinstead of usingmime_content_type. - Error Handling: The try/catch blocks help catch database issues or decoding failures, so you can give users clear feedback instead of a blank screen.
Quick Adjustment If You Used Raw BLOB
Just in case you ever switch to storing raw BLOB data (without base64), remove the base64_decode line and directly use $fileRecord['file_name'] as the raw content to output.
内容的提问来源于stack exchange,提问作者Dom

