通过 JavaScript 下载文件而不启动浏览器下载

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

Laravel 后端返回 StreamedResponse:

return Storage::download($filePath);

在前端我有以下内容:

async download(patientId, filename) {
    let queryParams = new URLSearchParams();
    queryParams.set('filename', filename);

    await ApiService.get(documentsUrl, queryParams);
}

由 VueJS 组件调用:

<base-card class="document text-center" @click="document.download(file.filename)">

响应标头包含浏览器启动下载所需的所有值:

Content-Type: application/pdf
Content-Length: 95561
Content-Disposition: attachment; filename=test_file.pdf

我还尝试添加一个分配 blob URL 的锚点并触发单击事件,结果始终相同:HTTP 响应成功,响应中具有适当的标头和二进制文件,但没有下载。

javascript laravel download
1个回答
0
投票

确保您的 ApiService.get 方法正确处理响应。确保它将响应识别为文件下载并将其处理。如果后端返回流,您的前端代码应该能够处理它。

async download(patientId, filename) {
    let queryParams = new URLSearchParams();
    queryParams.set('filename', filename);

    // Ensure that the responseType is set to 'blob'
    const response = await ApiService.get(documentsUrl, queryParams, { responseType: 'blob' });

    // Process the blob response, for example, creating a blob URL and triggering download
    const blob = new Blob([response.data]);
    const url = window.URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
}

并确保您的后端和前端位于同一域中,或者您的后端配置为正确处理

cross-origin requests
。 CORS 标头可能会影响浏览器处理响应的方式。

或者不要依赖浏览器的默认行为,而是尝试不同的方法,例如使用库进行文件下载或触发下载的不同方法。

例如,您可以使用文件保护程序库:

npm install file-saver

import { saveAs } from 'file-saver';

async download(patientId, filename) {
    let queryParams = new URLSearchParams();
    queryParams.set('filename', filename);

    const response = await ApiService.get(documentsUrl, queryParams, { responseType: 'blob' });

    // Use file-saver to trigger the download
    saveAs(response.data, filename);
}

© www.soinside.com 2019 - 2024. All rights reserved.