Javascript 使用ajax请求在浏览器中下载

Javascript 使用ajax请求在浏览器中下载,javascript,php,ajax,angularjs,fpdf,Javascript,Php,Ajax,Angularjs,Fpdf,我正在使用AngularJS,并试图用php生成PDF。这是我在controller.js中的内容: 在我的php文件中,我使用以下内容创建PDF: 但是请求是响应此请求,而不是打开保存对话框来保存我的pdf %PDF-1.3 30 obj endobj 40 obj 流动 x3Rð–2Ð35W(çr QÐw3T04Ó30PISp èZ*[è(hxèèèèè+è229;è(j*dÔ7W 尾流 endobj 10 obj < endobj 50 obj < endobj 20 obj endobj

我正在使用AngularJS,并试图用php生成PDF。这是我在controller.js中的内容:

在我的php文件中,我使用以下内容创建PDF:

但是请求是响应此请求,而不是打开保存对话框来保存我的pdf

%PDF-1.3 30 obj endobj 40 obj 流动 x3Rð–2Ð35W(çr QÐw3T04Ó30PISp èZ*[è(hxèèèèè+è229;è(j*dÔ7W 尾流 endobj 10 obj < endobj 50 obj < endobj 20 obj endobj 60 obj endobj 70 obj endobj 外部参照 0 8 0000000000 65535 f 0000000 228 00000 n 00000004160百万元 000000000 900万n 00000000 8700000N 0000000 315 00000 n 00000005200000000 n 000000059500000N 拖车 起始外部参照 644 %%EOF

我用过图书馆,这很有效:

$objWriter = PHPExcel_IOFactory::createWriter($ea, 'Excel2007');

// We'll be outputting an excel file
header('Content-type: application/vnd.ms-excel');

// It will be called Submission on [date_now].xls
header('Content-Disposition: attachment; filename="' . $filename . '.xls' . '"');

// Write file to the browser
$objWriter->save('php://output');
现在,我如何使我的PDF工作

更新:

我已将代码编辑为:

$pdf = new FPDF();

$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');

$filename = DXS_VKGROUP_PLUGIN_LIB_DIR . 'uploads/' . $_POST['fid'] . '.pdf';

$pdf->Output($filename, 'F'); // Save file locally

header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application-download');
header('Content-Length: ' . filesize($filename));
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="' . $filename . '"');

$handle = fopen($filename, 'rb');
fpassthru($handle);
fclose($handle);
该文件保存在本地,但下载不起作用。它无法让我的用户打开保存pdf的对话框。我做错了什么

更新2

我现在尝试在
application/pdf
中更改
应用程序下载
。他将文件保存在本地,但我没有获得下载对话框

响应如下(当我在Chrome中检查网络时):

%PDF-1.3 30 obj endobj 40 obj 流动 x3Rð–2Ð35W(çr QÐw3T04Ó30PISp èZ*[è(hxèèèèè+è229;è(j*dÔ7W 尾流 endobj 10 obj < endobj 50 obj < endobj 20 obj endobj 60 obj endobj 70 obj endobj 外部参照 0 8 0000000000 65535 f 0000000 228 00000 n 00000004160百万元 000000000 900万n 00000000 8700000N 0000000 315 00000 n 00000005200000000 n 000000059500000N 拖车 起始外部参照 644 %%EOF

根据,您可以将第二个参数设置为
D

$pdf->Output('Order123.pdf', 'D');
如果您希望自己使用保存的文件处理所有详细信息,以下是我向浏览器展示PDF的方式,以便从PHP下载:

header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application-download');
header('Content-Length: ' . filesize('file.pdf'));
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="file.pdf"');
$handle = fopen('file.pdf', 'rb');
fpassthru($handle);
fclose($handle);
更新:

请验证PDF文件是否已生成。web服务器进程是否具有该路径的写访问权限?是否正确包含FPDF?我在测试虚拟机上生成了此文件,它提供了一个文件
1.PDF
,供下载,该文件打开并包含“Hello World!”:


更新

使用FileSaver.js的方法也不起作用,似乎无法单独通过JavaScript强制调用本机“另存为”对话框,唯一的例外是IE的saveAs
execCommand
。检查

在项目中包含作为依赖项

更改
下载PDF
功能如下

 $scope.downloadPDF = function() {
    $http.post('/download-pdf', {
        fid: $routeParams.fid
      }, {
        responseType: 'arraybuffer'
      })
      .success(function(data, status, headers, config) {
        // Convert response data to Blob
        var file = new Blob([data], {
          type: 'application/pdf'
        });
        // Call the File Saver method to save the above Blob,this will show Save As dialog
        saveAs(file, "test.pdf");
      })
      .error(function(data, status, headers, config) {
        console.log("error");
      });

 };
Blob
对象可以在大多数现代浏览器中使用,但对IE<10的支持有限,请检查是否有多边形填充

同时删除
Content-Disposition:attachment
Content-Type:application-download
标题,因为我们不希望浏览器以本机方式处理下载过程


这是一个正在运行的演示,它显示了使用ajax获取PDF请求是不可能的。
相反,您可以做的是,通过javascript表单提交点击您的操作

e、 例如,
document.getElementById(formID).action=actionName

document.getElementById(formID).submit();  
这里formID是表单的id,
actionName
将是您指定的
'/download pdf'

在action类中,设置响应头

getResponse().setContentType("application/pdf");
getResponse().setHeader("Content-Disposition",  " attachment; filename= "+"pdffile.pdf");
这将导致您的文件以filename=pdffile.pdf下载。

这在(仅)AJAX中是不可能的

这里可以使用两种主要技术,这两种技术都不需要使用JavaScript来执行实际下载。一般的想法是将浏览器重定向到将提供所需文档的资源;如果重定向到下载,它将不会离开页面,而是显示保存对话框。中讨论了类似的主题。

获取请求 调整服务器端脚本以使用
$\u GET['fid']

后请求 服务器创建一个资源,并使用可在其中找到资源的URL进行响应:

$http.post('/download-pdf', { fid: $routeParams.fid })
    .success(function(data, status, headers, config) {
        // follow location provided by server
        location.href = data.redirect_url;
        console.log("success");
    })
    .error(function(data, status, headers, config){
        console.log("error");
    });
在创建新资源后,调整服务器端脚本以返回适当的JSON响应

header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
或使用BLOB:

 $scope.downloadPDF = function() {
    $http.post('/download-pdf', {
        fid: $routeParams.fid
      }, {
        responseType: 'arraybuffer'
      })
      .success(function(data, status, headers, config) {

        var file = new Blob([data], {
          type: 'application/pdf'
        });
        var url = URL.createObjectURL(blob);
        window.location.href = url;
      })
      .error(function(data, status, headers, config) {
        console.log("error");
      });

 };
或者使用
下载
属性创建元素:

$scope.downloadPDF = function() {
    $http.get('http://46.101.139.188/demo.pdf', {
      }, {
        responseType: 'arraybuffer'
      })
      .success(function(data, status, headers, config) {

        var file = new Blob([data], {
          type: 'application/pdf'
        });
        var url = URL.createObjectURL(file);
        var a = document.createElement('a');
        a.setAttribute('download', 'download');
        a.setAttribute('href', url);

         var event = new MouseEvent('click', {
          'view': window,
          'bubbles': true,
          'cancelable': true
        });
        a.dispatchEvent(event);
      })
      .error(function(data, status, headers, config) {
        console.log("error");
      });
 };

将文档发送到给定的目标:浏览器、文件或字符串。对于浏览器,可以使用插件(如果存在)或强制下载(“另存为”对话框)

如果需要终止文档,该方法首先调用Close()

参数

名称:

文件名。如果未指定,文档将以doc.pdf的名称发送到浏览器(目标I)

dest

发送文档的目标。它可以采用以下值之一:

  • I:将文件内联发送到浏览器。如果 可用。选择“保存”时,将使用名称给定的名称 生成PDF的链接上的“as”选项
  • D:发送到浏览器并强制下载具有给定名称的文件 名字
  • F:保存到本地文件,文件名由name(可能是 包括路径)
  • S:以字符串形式返回文档。忽略名称

    • 让我向你建议一件事

      仅通过AJAX,您无法下载任何文件。您需要首先使用AJAX调用创建.zip文件,然后获得该文件路径,您必须打开
      $http.post('/download-pdf', { fid: $routeParams.fid })
          .success(function(data, status, headers, config) {
              // follow location provided by server
              location.href = data.redirect_url;
              console.log("success");
          })
          .error(function(data, status, headers, config){
              console.log("error");
          });
      
      header('Content-Type: application/octet-stream');
      header("Content-Transfer-Encoding: Binary");
      header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
      
       $scope.downloadPDF = function() {
          $http.post('/download-pdf', {
              fid: $routeParams.fid
            }, {
              responseType: 'arraybuffer'
            })
            .success(function(data, status, headers, config) {
      
              var file = new Blob([data], {
                type: 'application/pdf'
              });
              var url = URL.createObjectURL(blob);
              window.location.href = url;
            })
            .error(function(data, status, headers, config) {
              console.log("error");
            });
      
       };
      
      $scope.downloadPDF = function() {
          $http.get('http://46.101.139.188/demo.pdf', {
            }, {
              responseType: 'arraybuffer'
            })
            .success(function(data, status, headers, config) {
      
              var file = new Blob([data], {
                type: 'application/pdf'
              });
              var url = URL.createObjectURL(file);
              var a = document.createElement('a');
              a.setAttribute('download', 'download');
              a.setAttribute('href', url);
      
               var event = new MouseEvent('click', {
                'view': window,
                'bubbles': true,
                'cancelable': true
              });
              a.dispatchEvent(event);
            })
            .error(function(data, status, headers, config) {
              console.log("error");
            });
       };
      
      $http.post('www.abc.com/zipcreate', {'id': id}).then(function (zipurl) {
                          $window.location = zipurl;
                  });
      
      $window.location = 'abc.com/link';
      
        header("Content-type: application/octet-stream");
        header("Content-Disposition: attachment; filename=".$name);
        header("Pragma: no-cache");
        header("Expires: 0");
        readfile($file);
        exit;
      
      $(document).ready(function () {
                  $('#generaPdf').click(function (e) {
                  e.preventDefault();
                  var name = $('#name').val();
                  $.ajax
                      ({
                          type: "POST",
                          url: "pdf.php",
                          data: { "name": name },
                          success: function (data) {
                              alert("todo ok")
                              location.href = "pdf.php"
                              // $('.result').html(data);
                              // $('#contactform')[0].reset();
                          }
                      });
                  });
              });
      
      <button type="submit" class="btn btn-primary" id="generaPdf"><i class="fas fa-link"></i> Generar documento para impresión</button>