将文件插入到SQL数据库中并检索它

时间:2018-12-06 21:46:50

标签: php sql sql-server file

我学校的网络服务器不允许我们使用move_uploaded_file(….)将文件上传到它。因此,我试图学习如何将PDF文件插入到提交的SQL Server数据库中,并在以后检索它。我可以使用以下代码放入PDF文件。但是通过浏览器部分检索文件不起作用。它仅打印文件的值,而不将文件保存到我的计算机中。任何帮助将不胜感激

<?php
//Connection get established successfully
$connInfo = array(//code omitted);
$connect = sqlsrv_connect(//code omitted, $connInfo) or die(print_r(sqlsrv_errors(SQLSRV_ERR_ALL), true));

if(isset($_POST['upload'])) //This part works
{
    // extract file name, type, size and path
    $file_path=$_FILES['pdf']['tmp_name']; //pdf is the name of the input type where we are uploading files
    $file_type=$_FILES['pdf']['type'];
    $file_size=$_FILES['pdf']['size'];
    $file_name=$_FILES['pdf']['name'];

    // checks whether selected file is a pdf file or not
    if ($file_name != "" && $file_type == 'application/pdf')
    {//PDF file may contains, images, tables, etc.. 
        $data = base64_encode(file_get_contents($file_path));

        //SQL Data type is varchar(MAX). query to update file in database.
        $query="UPDATE TestTable SET Data='".$data."' WHERE ID=1";
        $result = sqlsrv_query($connection, $query); //query execution
        // Check if it was successful
        if($result)
            echo 'Success! Your file was successfully added!';
        else
            echo '<br>Error!:'.sqlsrv_errors();
    } 
    else 
    {
        echo 'Not a pdf file. Try again';
    }
}

if(isset($_POST['read'])) //Does not download the file!!
{
    //Query to fetch field where we are saving pdf file
    $sql = "SELECT Data FROM TestTable WHERE ID = '1'";
    $result2 = sqlsrv_query($connection, $sql);    // query execution
    $row = sqlsrv_fetch_object($result2); // returns the current row of the resultset
    $pdf_content = $row->Data; // Put contents of pdf into variable
    $fileName = time().".pdf"; // create the unique name for pdf generated
    //download file from database and allows you to save in your system
    header("Content-type: application/pdf");
    header("Content-disposition: attachment; filename=".$fileName);
    print $pdf_content;
}

?>

<form name="form" id="form" action="" method="post" enctype="multipart/form-data">
File: <input type="file" name="pdf" id="pdf" accept="application/pdf" title="Choose File" /><br />
<input type="submit" name="upload" id="upload" value="Upload" /><br />
<input type="submit" name="read" id="read" value="Read" />
</form>

我将文件的完整数据值保存到数据库字段中(不插入,更新现有行)。不尝试单独保存文件的路径或文本内容。这会将PDF文件保存到以base64_encode归档的数据库中。如果我在运行此代码后查看数据库的内容,则会发现该行已用类似于以下内容的内容进行了更新:JVBERi0xLjYNJeLjz9MNCjI0IDAgb2JqDTw8L0xpbmVhcml6ZWQgMS9MIDM1MTcyL08gMjYvRSAzMDI1Ni9OIDEvVCA .....

1 个答案:

答案 0 :(得分:0)

下一个示例演示如何将PDF文件插入SQL Server的varbinary(max)列,然后将该文件保存到磁盘:

T-SQL:

CREATE TABLE [dbo].[VarbinaryTable] (
    [Data] varbinary(max) NULL
)

PHP:

<?php
# Connection
$server = 'server\instance,port';
$database = 'database';
$uid = 'user';
$pwd = 'password';
$cinfo = array(
    "Database" => $database,
    "UID" => $uid,
    "PWD" => $pwd
);
$conn = sqlsrv_connect($server, $cinfo);
if ($conn === false)
{
    echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
    exit;
}

# Insert PDF file
$pdf = file_get_contents('PDFFile.pdf');
$sql = "INSERT INTO VarbinaryTable ([Data]) VALUES (?)";
# In your case:
# $sql = "UPDATE VarbinaryTable SET [Data] = ? WHERE ID = 1"; 
$params = array(
    array($pdf, SQLSRV_PARAM_IN, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY), SQLSRV_SQLTYPE_VARBINARY('max'))
);
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
    echo "Error insert (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
    exit;
}

# Get PDF file and save it again on disk. 
$sql = "SELECT [Data] FROM VarbinaryTable";
# In your case:
# $sql = "SELECT [Data] FROM VarbinaryTable WHERE ID = 1"; 
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
    echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
    exit;
}
if (sqlsrv_fetch($stmt)) {
    $pdf = sqlsrv_get_field($stmt, 0, SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY));
    file_put_contents('PDFFile-fromDB.pdf', $pdf);
}

# Output the file
header('Content-Description: File Transfer');
header("Content-type: application/pdf");    
header("Content-disposition: attachment; filename=PDFFile-fromDB.pdf");
header('Content-Length: ' . filesize("PDFFile-fromDB.pdf"));
readfile("PDFFile-fromDB.pdf");
?>