【问题标题】:Download txt file with laravel and axios用 laravel 和 axios 下载 txt 文件
【发布时间】:2020-05-25 15:11:08
【问题描述】:

你好 希望你会做得很好。我想从 laravel 的控制器下载动态生成的 txt 文件,我搜索了很多但找不到任何解决方案。请帮助我将非常感激。

带有 axios 请求的刀片代码

submitHandler:function(form,e){
            var btn=document.querySelector("#BtnSubmit");
            btn.style.display="none";var img=document.createElement("img");
            img.setAttribute("src",base_url+'front/images/loading.gif');
            var loader=document.querySelector("#loader");loader.appendChild(img);
            var url="<?php echo route('database.export-txtProcess');?>";
            var cur_url="<?php echo route('database.export-txt');?>";

            //var tblExportSelect  = $("#tblExportSelect").val();


            var pushArray = [];
            $.each($("#tblExportSelect option:selected"), function(){
            pushArray.push($(this).data("id"));
            });

            var data  = new FormData();

            data.append('tblExportSelect',pushArray);


            //$("#tblExportSelect").val(selected);


            axios({
                method: 'POST',
                url: url,
                data: data,
              })
            .then(function(res){
              console.log(res);
            })
         e.preventDefault();
      }
   });

控制器方法

public function exportTxtProcess(Request $request){

      /*dd($request->tblExportSelect);*/

       $tables  = explode(",", $request->tblExportSelect);

        $destinationPath = public_path('/');

        $result;

       foreach ($tables as $table) {
          $outputs   =  DB::select("SELECT * FROM $table");

          $today   = date("Y-m-d");
          $fileName  = $table."-".$today;
          $fp = fopen($destinationPath . "$fileName.txt","wb");

          foreach ($outputs  as $output) {
            $output  = (array)$output;

            @array_shift($output);

            $removeUserId  = @$output['user_id'];
            $created_at    = @$output['created_at'];
            $updated_at    = @$output['updated_at'];



            if (($key = array_search($removeUserId, $output)) !== false) {
                unset($output[$key]);
            }
            if (($key1 = array_search($created_at, $output))) {

                unset($output[$key1]);
            }

            if (($key2 = array_search($updated_at, $output))) {

                unset($output[$key2]);
            }

            if (is_null($created_at) OR $created_at == '') {
                unset($output['created_at']);
            }

            if (is_null($updated_at) OR $updated_at == '') {
                unset($output['updated_at']);
            }


            $netResult = $this->getTableFields($table,$output);

            fwrite($fp,$netResult);

          }

          $result = fclose($fp); 
       }
       /*$arr = array(['Good' => true,'message' => 'Data has been successfully imported.'], 200);
                    echo json_encode($arr);*/
       if ($result) {
        $pathToFile  = $destinationPath . "$fileName.txt";

        $downloaded = response()->download($pathToFile)->deleteFileAfterSend();


       }
    }

我想下载如上创建的 txt 文件,而不是在控制台中流式下载。

提前致谢

【问题讨论】:

  • 它是经过身份验证的 api 端点还是公共的?

标签: laravel laravel-5 download axios jquery-file-upload


【解决方案1】:

您必须传递标题。最重要的是,您没有返回响应。


   $headers = [
      'Content-type' => 'text/plain', 
      'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),
      'Content-Length' => sizeof($content)
    ];
        return response()->download($pathToFile, $fileName,$headers)->deleteFileAfterSend();

【讨论】:

  • @SadamHussain 你得到的错误是什么?
  • 兄弟请告诉我我已经尝试了编辑后的代码,但无法正常工作,它显示在浏览器中而不是下载。 @Adnan Mumtaz
  • 我没有收到错误消息。我正在控制台中查看 txt 内容而不是下载。@AdnanMumtaz
  • 没有错误,但响应中显示的是文件内容而不是下载。我想下载文件。@Adnan Mumtaz
  • @SadamHussain 可能有替代方案。您可以使用获取请求在新选项卡中打开它,然后下载文件。
猜你喜欢
  • 2014-07-12
  • 2019-08-17
  • 2022-06-13
  • 2021-06-25
  • 2020-02-26
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 2019-02-23
相关资源
最近更新 更多