如何解压缩来自MS SQL VarBinary的数据并另存为文件?(在 PHP 中)



我正在尝试从 php 中的Microsoft SQL varbinary 字段中检索文件。这些文件是使用 IO 压缩的。Compression.DeflateStream() 在插入数据库之前在 Visual Studio 程序中。

我可以从数据库中获取文件,但我不确定如何解压缩文件:

<?php
//assume that I already made the connection
$sql = "SELECT [FileData], [contentType] FROM dbo.Files where [FileGUID]='DAB88A50-E2C3-E311-A2D2-005056930304'";
$stmt= sqlsrv_query($conn , $sql);

if( $stmt === false ) {
if( ($errors = sqlsrv_errors() ) != null) {
foreach( $errors as $error ) {
echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
echo "code: ".$error[ 'code']."<br />";
echo "message: ".$error[ 'message']."<br />";
}
}
}
$result = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$filename = "test.pdf";
$X = $result['FileData'];
$contentType=  $result['ContentType'];
$filename=  $result['Filename'];

header("Content-Type:    $contentType; charset=utf-8");
header("Content-Disposition: attachment; filename=$filename");  //File name extension was wrong
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

//$X =  unpack('H*hex', $X);
echo $X;
?>

上面的 PHP 获取文件,但它仍然是压缩格式。

在 VB 中,我可以使用以下代码解压缩 get 文件:

Dim Decompressed As Byte()
Using ms As New IO.MemoryStream(b)
Dim msOut As New IO.MemoryStream()
Dim ds As New IO.Compression.DeflateStream(ms, IO.Compression.CompressionMode.Decompress)
ds.CopyTo(msOut)
Dim strPath As String = "d:fsout" + strDBName
If (Not System.IO.Directory.Exists(strPath)) Then
System.IO.Directory.CreateDirectory(strPath)
End If
Dim file As New FileStream(strPath + "" + strFilename, FileMode.Create, FileAccess.Write)
msOut.WriteTo(file)
file.Close()
ms.Close()
ds.Close()

不过,我希望能够在PHP中做到这一点。有人知道在PHP中解压缩文件的技巧吗?我有一种感觉,这与 php 中的"unpack()"有关,但不确定要使用哪些参数。

回答我自己的问题

.NET 使用 zlib 在 IO 中进行压缩。Compression.DeflateStream()

所以我需要做的是:

$uncompressed = zlib_decode($X);
echo $uncompressed;

实际上在 php 中比 VB 容易得多。

我的完整代码是:

<?php
//assume that I already made the connection
$sql = "SELECT [FileData], [contentType] FROM dbo.Files where [FileGUID]='DAB88A50-E2C3-E311-A2D2-005056930304'";
$stmt= sqlsrv_query($conn , $sql);

if( $stmt === false ) {
if( ($errors = sqlsrv_errors() ) != null) {
foreach( $errors as $error ) {
echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
echo "code: ".$error[ 'code']."<br />";
echo "message: ".$error[ 'message']."<br />";
}
}
}
$result = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$filename = "test.pdf";
$X = $result['FileData'];
$contentType=  $result['ContentType'];
$filename=  $result['Filename'];

header("Content-Type:    $contentType; charset=utf-8");
header("Content-Disposition: attachment; filename=$filename");  //File name extension was wrong
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

//$X =  unpack('H*hex', $X);
echo $X;
?>

相关内容

  • 没有找到相关文章

最新更新