1

我在 Vue.js 中下载 .zip 文件时遇到问题。这是我的代码。

if (response) {
                    let fileName = response.headers["x-suggested-filename"]
                    var fileUrl = window.URL.createObjectURL(new Blob([response.data], {type: "application/zip"}));
                    var fileLink = document.createElement("a");
                    fileLink.href = fileUrl;
                    fileLink.setAttribute("download", fileName);
                    document.body.appendChild(fileLink);
                    fileLink.click();
                } else {
                    this.$notify.error({
                        title:    "Request failed",
                        message:  "No response received. ",
                        duration: 0,
                    });
                }

这是我的响应标题

Vue.js

我下载了文件,但它不起作用。

我存档实用程序失败。

但是链接它的工作,这意味着,后端站点没有问题。我怎样才能修复这个错误?

这是我来自服务器的代码。

public function export(array $params)
{
    if (!$this->load($params, '') || !$this->validate()) {
        throw new BadRequestHttpException();
    }

    $exporter = new ProfileExporter($this->format);
    $zipFile = new ZipFile();

    $exporter->exportToZipFile($zipFile, $this->profileId, $params);
    $fileName = 'df-profile-data-export-' . \Yii::$app->formatter->asDate('now', 'yyyy-MM-dd') . '.' .
        $this->getFileExtension();

    $stream = fopen('php://memory', 'w+');
    $zipFile->writeToStream($stream);
    \Yii::$app->response->headers->add('X-Suggested-Filename', $fileName);

    \Yii::$app->response->sendStreamAsFile($stream, $fileName, [
        'mimeType' => 'application/zip',
    ]);
}
4

1 回答 1

2

要通过 axios 下载文件,您应该在 axios 标头中设置 responseType

responseType:'blob'
于 2020-08-14T09:46:44.453 回答