在 PHP 中写入文件,然后下载它


Write to a file in PHP and then download it

我正在处理一个项目,我在其中获取文件流并将该文件写入服务器本地磁盘。

然后我希望PHP下载它,但它只是将文件的数据转储到页面。

以下是我编写文件并尝试告诉 PHP 下载它的方式

$settingsManager = new SettingsManager();
$this->tempWriteLocation = $settingsManager->getSpecificSetting("hddFileWriterLocation");
$downloadUrl = $settingsManager->getSpecificSetting("tempFileUrlDownload") . "/$this->tempFileName";
if (!$this->checkIfDirectoryExists())
{
     throw new Exception("Failed to create temp write directory: $this->tempWriteLocation");
}
$filePathAndName = "$this->tempWriteLocation''$this->tempFileName";
$fh = fopen($filePathAndName, "w");
if (!$fh)
{
     throw new Exception("Failed to open file handle for: $filePathAndName. " . error_get_last());
}
fwrite($fh, $this->fileData);
fclose($fh);
//return $downloadUrl;
header('Content-Description: File Transfer');
header('Content-Type: audio/wav');
header('Content-Disposition: attachment; filename='.basename($filePathAndName));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filePathAndName));
ob_clean();
flush();
readfile($filePathAndName);

当上面的代码运行时,我得到以下输出(只是一个片段(

RIFF''tWAVELIST2INFOISFT%Aculab Media System Server V2.3.4b11fmt @@fact sdata sUU UUUUUU UUU U UUU

只是为了让你知道钻石是我回来的实际输出,堆栈溢出正确显示某些内容没有任何问题。

我尝试将内容类型设置为强制下载,但没有任何区别。

试试这个标题:

header('Content-type: audio/x-wav', true);
header('Content-Disposition: attachment;filename=wav-filename.wav');

看看这是否有效。从我所看到的情况来看,您的代码形成设置正确。修复标头应自动下载文件。