我会将这个示例发布给sqlsrv DB中需要插入文件到varbinary(max)字段帮助的人。 此外,如果您需要从varbinary字段中读取,您可以看到我是如何做到的。 此代码正常运行,但欢迎您提出所有意见和建议。 这是样本表:
CREATE TABLE [dbo].[files]
(
[id] [int] NOT NULL IDENTITY(1, 1),
[content] [varbinary] (max) NULL,
[filename] [varchar] (max) COLLATE Croatian_CI_AS NULL
)
首先输入您使用的服务器的数据。 如果需要在db:
中的varbinary字段中插入文件<?php
$server = "";
$konekcionistring = array( "Database"=>"", "UID"=>"", "PWD"=>"");
$konekcija = sqlsrv_connect( $server, $konekcionistring);
$newfileName = 'testX.pdf';
$newtmpName = 'C:\xampp\htdocs\testX.pdf';
$fp = fopen($newtmpName, 'rb');
$file_content = fread($fp, filesize($newtmpName));
fclose($fp);
$sql = "INSERT INTO files ([content],[filename]) SELECT CONVERT(VARBINARY(MAX),?),?";
$parametri = array(
array($file_content),
array($newfileName)
);
$r_blob = sqlsrv_query($konekcija, $sql, $parametri);
if( $r_blob === false)
{
die( print_r( sqlsrv_errors(), true) );
}
?>
当您需要从DB中的varbinary字段读取数据时,您可以使用以下代码:
<?php
$server = "";
$konekcionistring = array( "Database"=>"", "UID"=>"", "PWD"=>"");
$konekcija = sqlsrv_connect( $server, $konekcionistring);
$skript = "SELECT F.content, F.filename AS Template FROM dbo.files AS F";
$izvrsiSQL = sqlsrv_query($konekcija, $skript);
$result = sqlsrv_fetch_array($izvrsiSQL, SQLSRV_FETCH_ASSOC);
$filename = $result['filename'];
$X = $result['content'];
header("Content-type:application/pdf");
header('Content-Disposition: attachment inline; filename="'.$filename.'"');
echo $X;
?>
如果您有任何意见或建议,欢迎您。
答案 0 :(得分:0)
如果你想压缩和上传
function compressImage($filename){
$details = getimagesize($filename);
$content = file_get_contents($filename);
$srcImg = imagecreatefromstring($content);
//get content
ob_start();
imagejpeg($srcImg, null,10);
$contents = ob_get_contents();
ob_end_clean();
imagedestroy($srcImg);
return $contents;
}
$CompressedImage = compressImage($FileTempName);
$status = sqlsrv_query($conn,'insert into Post (P_image) values (?)', array(
array($CompressedImage, SQLSRV_PARAM_IN,SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY), SQLSRV_SQLTYPE_VARBINARY('max'))
));