失败,zip 文件通过 axios 从 vuejs 下载

Posted

技术标签:

【中文标题】失败,zip 文件通过 axios 从 vuejs 下载【英文标题】:failed, zip file Download via axios from vuejs 【发布时间】:2020-12-04 04:07:12 【问题描述】:

我在 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,
                    );
                

这是我的回复标题

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

但是链接可以工作,这意味着,后端站点没有问题。 我该如何解决这个错误?

这是我的服务器代码。

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',
    ]);

【问题讨论】:

能否将您的代码添加为文本?这使得使用更正的版本更容易阅读和回答 当然。已添加 那是..仍然是图像。现在,即使有了服务器代码的第二张图片。 删除图片并将代码粘贴为文本 好的。我做。 :) 【参考方案1】:

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

responseType:'blob'

【讨论】:

以上是关于失败,zip 文件通过 axios 从 vuejs 下载的主要内容,如果未能解决你的问题,请参考以下文章