【问题标题】:How can i force download files with Vue + Laravel如何使用 Vue + Laravel 强制下载文件
【发布时间】:2021-02-17 19:04:16
【问题描述】:

我正在尝试使用从 laravel 检索的 vue 强制下载文件(不一定是 PDF!)。

我环顾四周,我似乎只能找到方法,因为我知道它总是会是 PDF。但是,如果可能有几种不同的文件类型怎么办。

【问题讨论】:

    标签: laravel vue.js download axios


    【解决方案1】:

    使用 laravel,你可以编写函数下载。也许

    $file_url = 'http://www.myremoteserver.com/file.exe';
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
    readfile($file_url);
    

    示例文件下载是 docx 文件然后内容类型是 docx 的 mime => application/vnd.openxmlformats-officedocument.wordprocessingml.document

    有了vue,就可以使用axios下载文件了。

    【讨论】:

      【解决方案2】:

      我使用此代码下载任何文件。(您必须根据需要对其进行自定义):

      vuejs 组件:

      axios.get( 'user/getTicketFile', {
              params: { 
                number: this.$route.params.id,
                name: item
               }, 
                responseType: 'blob'
              })
              .then(function (r) 
              {
                const url = window.URL.createObjectURL(new Blob([r.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', 'file.'+r.headers.ext); //or any other extension
                document.body.appendChild(link);
                link.click();
      
                //hide loader
                i.loader = false
            });
      
          },
      

      这是 laravel 后端函数示例:

      public function getTicketFile(Request $request)
          {
              $number = $request['number'];
              $name = $request['name'];
              
              $filePath = storage_path( 'app/tickets/'.$number.'/'.$name );
      
              if( file_exists($filePath) )
              {
                  $headers = array(
                      'ext' => pathinfo($name, PATHINFO_EXTENSION),
                  );
                  return response()->download($filePath, '', $headers);
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-13
        • 2021-07-31
        • 2011-11-08
        • 1970-01-01
        • 2021-02-08
        • 1970-01-01
        • 2018-11-17
        • 2011-11-12
        • 2020-10-31
        相关资源
        最近更新 更多