使用Oracle和PHP下载BLOB文件

时间:2010-08-10 15:44:46

标签: php oracle oracle10g blobs

使用PHP,我正在尝试下载已上传到Oracle 10g数据库的blob文件。我已经看到并模仿了我发现的许多例子。当我访问该页面时,会出现一个“文件下载”对话框,允许我打开或保存。如果我单击“打开”,则媒体播放器会出现,但从不检索文件。如果我选择保存,我总会收到一条错误消息,指出“Internet Explorer无法打开此Internet站点。请求的站点不可用或无法找到。请稍后再试。”

下面是我的代码,它很简单,就像我找到的例子一样。

<?php

header('Content-Disposition: attachment; filename='.$_GET['fileName']);
header('Content-length: '.$_GET['fileSize']);
header('Content-type: '.$_GET['mimeType']);

require_once("Include/Application.php");

$connection = oci_connect ($userID, $password, $TNS);

$phpCur = oci_new_cursor($connection);
$stmt = oci_parse($connection, "BEGIN MOR.DOWNLOAD_ATTACHMENT (:morID, :attachmentType, :phpCur); END;");
oci_bind_by_name($stmt, ":morID", $_GET['morID'], -1);
oci_bind_by_name($stmt, ":attachmentType", $_GET['attachmentType'], -1);
oci_bind_by_name($stmt, "phpCur", $phpCur, -1, OCI_B_CURSOR);
oci_execute($stmt);
oci_free_statement($stmt);

$output = '';
oci_execute($phpCur);
while( $row = oci_fetch_array($phpCur) )
    $output .= $row['ATTACHMENT_BL'];

oci_free_statement($phpCur);

oci_close($connection);

echo $output;

exit;

?>

2 个答案:

答案 0 :(得分:0)

为您的脚本添加更多错误处理。任何oci *函数都可能失败,然后后续步骤也将失败。 documentation告诉您如果函数失败以及返回值将会发生什么。 E.g。

返回值
错误时返回连接标识符或FALSE。

如果您尽可能晚地设置Content-type标头,即在第一个输出之前,您可以发送包含某种错误消息的纯文本或html。

<?php
// error_reporting/ini_set: for testing purposes only.
error_reporting(E_ALL); ini_set('display_errors', 1);

require_once("Include/Application.php");

$connection = oci_connect ($userID, $password, $TNS);
if ( !$connection) {
  die('database connection failed');
}

$phpCur = oci_new_cursor($connection);
if ( !$phpCur) {
  die('creating cursor failed');
}

$stmt = oci_parse($connection, "BEGIN MOR.DOWNLOAD_ATTACHMENT (:morID, :attachmentType, :phpCur); END;");
if ( !$stmt) {
  die('creating statement failed');
}

// and so on and on. Test the return values of each oci* function.

oci_close($connection);

header('Content-Disposition: attachment; filename='.$_GET['fileName']); // at least at basename() here
header('Content-length: '.$_GET['fileSize']); // strange...
header('Content-type: '.$_GET['mimeType']); // possible but still strange...
echo $output;
exit;

答案 1 :(得分:0)

使用你的数据库查询,首先在这里是数据字段是blob数据:

$sql="SELECT FILE_NAME,data,length(data) as filesize  FROM branch_data where id='$id'";
$r = $db->execute($sql);
$filename=$r->data[0]['FILE_NAME'];
$d=$r->data[0]['DATA'];
$filesize = $r->data[0]['FILESIZE'];
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' .$filesize);  
echo $d->load();