代码之家  ›  专栏  ›  技术社区  ›  calin24

下载一个带有javascript的url文件,然后打开该文件

  •  0
  • calin24  · 技术社区  · 7 年前

    我想使用javascript/jquery从服务器下载一个文件。

    按钮:

    <a class="btn btn-primary" id="exportInvoice">Export XML</a>
    

    ajax请求:

    $('#exportInvoice').on('click', function () {                
         $.ajax({
               type: 'POST',
               dataType: 'json',
               url: '{{ route('export-xml') }}',
               data: {dateRange: dateRange},
               success: function (resp) {                        
                    if(resp.error){
                        // error
                        alert(resp.msg);
                    } else {
                        // success
                        alert(resp.msg);
                        window.location=resp.url;
                    }
                }
           });
    })
    

    我正在使用laravel5.7blade生成url。

    当我单击按钮时,文件将打开而不是下载(因为窗口的原因。location=resp.url;

    我在想。。。在进行ajax调用之后(当成功响应时)。。。。正在将下载属性和href设置为链接。。。。但是我需要再次调用click事件来下载文件。

    如何下载打开的文件???

    2 回复  |  直到 7 年前
        1
  •  3
  •   DarkSuniuM Mirko Jelic    7 年前
    window.location.href = resp.url
    

    这将在同一个页面中开始下载,就像您在没有任何目标的情况下单击链接一样 _self .

        2
  •  0
  •   calin24    7 年前

    创建用于下载文件的隐藏窗体:

    隐藏形式:

    <form id="downloadXmlForm" method="post" action="{{ route('download-xml-invoices') }}" style="display: none">
         <input type="hidden" name="xmlFileName">
         <button type="submit" class="btn btn-primary">Export XML</button>
         ({ csrf_field() }}
    </form>
    

    从ajax请求接收后(成功时)=>提交表格以下载文件:

    $('input[name="xmlFileName"]').val(resp.fileName);                                
    document.getElementById('downloadXmlForm').submit();
    

    在后端,对ajax请求的响应是:

    ...
    $fileName = uniqid().'.xml';
    $xmlFilePath = storage_path('invoices/'.$fileName);
    file_put_contents($xmlFilePath, $xmlString);
    
    return response()->json(['error' => false, 'msg' => $message, 'fileName' => $fileName]);
    

    表单提交时调用的下载功能:

    public function downloadInvoicesXml(Request $request){
        return response()->download( storage_path('invoices/'.$request->input('xmlFileName')));
    }
    

    如果有人有更好的主意,请告诉我:)