开发者

How to store a PDF file in MySQL database?

开发者 https://www.devze.com 2023-01-17 05:09 出处:网络
How to store a PDF file in a MySQL database using 开发者_JS百科PHP?Using BLOB (Binary Large Object) (longblob datatype)

How to store a PDF file in a MySQL database using 开发者_JS百科PHP?


Using BLOB (Binary Large Object) (longblob datatype)

$fileHandle = fopen($fileUpload, "r");
$fileContent = fread($fileHandle, $fileUpload_size);
$fileContent = addslashes($fileContent);
$dbQuery = "INSERT INTO myBlobs VALUES ";
$dbQuery .= "('$fileContent')";

The full tutorial available here

but it's strongly recommended to store files on the file system, and just add a reference in the DB (a field with the file path and name). Several reasons:

  • Faster
  • Easier to access (don't need any special application)
  • Faster backups
  • Less space


Use a type BLOB.

Here's an example in PHP


As others mentioned, you can use a BLOB type.

Alternatively, what you can also do is save the PDF in the file system and save the relative link to it into the database. This is the same principle that applies for saving things such as Thumbnails and other data types that may be unique to the user and are expensive in terms of resources.


If you are simply looking to store uploaded PDF files on your server, it's more common to copy the file to a given directory with a unique filename and simply store the full path of that file in your MySQL table.

If you are definitely looking to store the full binary data of the file in your MySQL database, then you will have to do a little more work to put the binary data into a BLOB field in MySQL and then to turn it back into a file when you pull it out again at a later date.

You will probably want to store not only the binary data for the file in your MySQL table, but also the filename, filetype and possibly even the size of the file (for listing on your webpage). You will probably want a table such as;

CREATE TABLE files (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  filename VARCHAR(128) NOT NULL,
  mimetype VARCHAR(64) NOT NULL,
  data MEDIUMBLOB NOT NULL
);

In your PHP, you can then insert an uploaded file with something like the following;

$filePointer = fopen($_FILES['fileUpload']['tmp_name'], 'r');
$fileData = fread($filePointer, filesize($_FILES['fileUpload']['tmp_name']));
$fileData = addslashes($fileData);
$sql = "INSERT INTO files (filename, mimetype, data) VALUES( $fileName, $fileType, $fileData )";

Getting the file back out again will required a dedicated script that selects the appropriate file and then uses a series of 'header' commands to push that file back down to the browser with in a form that the browser knows how to handle it.

You can read a full tutorial about this here.

0

精彩评论

暂无评论...
验证码 换一张
取 消