【发布时间】:2019-05-08 16:01:00
【问题描述】:
我学校的网络服务器不允许我们使用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 .....
【问题讨论】:
-
我在这里没有看到 INSERT,只是一个 UPDATE。
-
还不清楚您是要保存文件的路径,还是保存为 BLOB。
-
查看编辑:栏的类型是什么?这需要是一个 BLOB。你可以在这里
@Funk我或@someone_else。我们不能一直看这里的问题。 -
你是对的;请改用
varbinary/varbinary(MAX)。我的 SQL 服务器技能不像 MySQL。 -
嗯...,我会尝试丢失
base64_encode()并使用准备好的语句,如this Q&A。和/或stackoverflow.com/q/33630714/1415724 和stackoverflow.com/questions/43071537/…
标签: php sql sql-server file