【问题标题】:Download link excel in vuejs在 vuejs 中下载链接 excel
【发布时间】:2021-07-12 09:14:31
【问题描述】:

在控制器 laravel 中:我使用 box/spout ,我将 excel 文件保存在单独的文件夹中,并创建一个指向保存文件的文件夹的变量,然后返回 vuejs 视图以下载该文件

$path = '/files/'.$name;
$urlFile = url('/files/'.$name);
var_dump($urlFile);
// Result:
http://localhost.loca/file/data.xlsx

我返回视图 vuejs:

return response()->json($urlFile);

查看 vuejs:

    methods: {
      // event button click
      clickButton() {
        axios
        .get("/api/export")
        .then((res) => {
          console.log(res.data) // http://localhost.loca/file/data.xlsx
         // I want to download this link !
        })
        .catch((error) => {
          console.log(error);
        });
       }
     }

请给我想法下载链接?谢谢

更新:我使用window.open(res.data),但它不起作用

【问题讨论】:

    标签: laravel vue.js vuejs2


    【解决方案1】:

    尝试创建一个锚点并以编程方式单击它以下载文件:

    
    .then((res) => {
              console.log(res.data) // http://localhost.loca/file/data.xlsx
      //create and append anchor download to body
      const downloadAnchor = document.createElement("a");
      downloadAnchor.setAttribute("href", "http://localhost.loca/file/data.xlsx");
      downloadAnchor.setAttribute("download", "data.xlsx");
      document.body.appendChild(downloadAnchor);
      downloadAnchor.click();
      //remove anchor download
      document.body.removeChild(downloadAnchor);
    
    })
    

    【讨论】:

      【解决方案2】:

      如果window.open 不起作用,您可以试试这个:

      function download(url) {
        const a = document.createElement('a')
        a.href = url
        a.download = url.split('/').pop()
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
      }
      

      然后在你的方法中调用下载函数:

          methods: {
            // event button click
            clickButton() {
              axios
              .get("/api/export")
              .then((res) => {
                console.log(res.data) // http://localhost.loca/file/data.xlsx
                download(res.data)
              })
              .catch((error) => {
                console.log(error);
              });
             }
           }
      

      【讨论】:

      • 谢谢兄弟。我下载了它,但由于某种原因,当我打开 excel 文件时,它显示"Excel cannot open the file"。但是原来的excel文件还是可以打开的
      猜你喜欢
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      • 1970-01-01
      • 2021-09-22
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      相关资源
      最近更新 更多