我正在尝试从php中的Microsoft SQL varbinary字段中检索文件。在插入数据库之前,这些文件在Visual Studio程序中使用IO.Compression.DeflateStream()进行压缩。
我可以从数据库中获取文件,但我不确定如何解压缩文件:
<?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;
?>