在浏览器中下载 Laravel 10 中的文件

问题描述 投票:0回答:1

嗨,我使用 Jasper 创建文件,现在我想做的是,当用户按下按钮时,他将开始下载这些文件,但是当我尝试时,响应代码是 200,但设备上下载的弹出窗口没有发生。文件保存在应用程序中的我的文件夹中。

这是那部分代码;

 public function generateReport(array $parameters, string $fileName, $request)
    {
        //Checking and getting formats from request
        $acceptedFormats = [
            'PDF', 'XLS', 'XLSX', 'DOCX', 'PPTX', 'CSV', 'HTML', 'RTF', 'TXT', 'XML',
            'ODT', 'ODS',
        ];

        $jsonBody = $request->getContent();
        $requestData = json_decode($jsonBody, true);
        $formats = $requestData['formats'] ?? [];

        foreach ($formats as $format) {
            if (!in_array(strtoupper($format), $acceptedFormats)) {
                throw new \InvalidArgumentException('Invalid format: ' . $format);
            }
        }

        //Fetching, preparing and creating files
        $jrxmlFile = __DIR__ . '\Reports\Template\\JasperFiles\\' . $fileName . '.jrxml';

        $jasper = new PHPJasper();
        $jasper->compile($jrxmlFile)->execute();

        $jasperFile = __DIR__ . '\Reports\Template\\JasperFiles\\' . $fileName . '.jasper';
        $outputFile = __DIR__ . '\Reports\Output\\' . $fileName;

        $jasperConfig = config('jasper.db_connection');
        $options = [
            'format' => $formats,
            'params' => $parameters,
            'db_connection' => $jasperConfig
        ];


        //Where the magic happens
        $jasper->process(
            $jasperFile,
            $outputFile,
            $options,
        )->execute();



        $filePath = $outputFile . '.pdf';
        $headers = [
            'Content-Type' => 'application/pdf',
        ];
        return response()->download($filePath, $fileName, $headers);
    }

文件创建工作正常,但我可以让它开始下载,这里是 FE 的 api:

    export async function generateReportForOneProduct(
    id: number,
    body: { formats: string[] }
) {
    try {
        const response = await axios.post(
            `${process.env.NEXT_PUBLIC_URL}/api/product/${id}/generateReport`,
            {
                formats: body.formats.map((format) => format.toLowerCase()),
            },
        );
        return response.data;
    } catch (error) {
        console.error("Error inserting variant:", error);
        throw error;
    }
}

任何帮助都会很棒。谢谢:)

php laravel file download
1个回答
0
投票

您必须创建一个链接并触发点击它。之后您可以删除链接。

const fileURL = window.URL.createObjectURL(new Blob([response.data]))

const link = document.createElement('a')
link.href = fileURL
link.setAttribute('download', `file_name.pdf`)
document.body.appendChild(link)
link.click()
link.remove()
window.URL.revokeObjectURL(fileURL)
© www.soinside.com 2019 - 2024. All rights reserved.