在API Platform中,可以使用Symfony HTTP基础组件提供的FileResponse类来快速地实现文件下载操作,并添加正确的Content-Type头。 以下是代码示例:
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\FileInterface;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class DownloadController
{
/**
* 下载一个文件
*
* @param int $id 文件ID
*
* @return BinaryFileResponse
*
* @throws FileNotFoundException if the file cannot be found
*/
public function downloadFileAction(int $id): BinaryFileResponse
{
// 从数据库或文件系统中获取文件
$file = $this->getFilePathById($id);
if (!$file instanceof FileInterface) {
throw new FileNotFoundException();
}
// 生成响应对象
$response = new BinaryFileResponse($file);
// 设置下载时的文件名
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $file->getFilename());
// 设置文件的Content-Type
$response->headers->set('Content-Type', $file->getMimeType());
return $response;
}
private function getFilePathById(int $id): ?FileInterface
{
// 从数据库或者文件系统中获取文件
// 返回一个Symfony\Component\HttpFoundation\File\FileInterface实例或null
}
}