sourcecode

Ajax 요청을 사용하여 브라우저에서 다운로드

copyscript 2023. 2. 15. 22:08
반응형

Ajax 요청을 사용하여 브라우저에서 다운로드

Angular와 함께 일하고 있습니다.JS와 저는 php로 PDF를 생성하려고 합니다.컨트롤러에는 다음과 같은 기능이 있습니다.js:

$scope.downloadPDF = function(){
    $http.post('/download-pdf', { fid: $routeParams.fid })
        .success(function(data, status, headers, config){
            console.log("success");
        })
        .error(function(data, status, headers, config){
            console.log("error");
        });
};

내 php 파일에는 FPDF 라이브러리를 사용하여 PDF를 작성하기 위한 다음 내용이 있습니다.

function download_pdf()
{
    $id = $_POST['fid'];

    $pdf = new FPDF();

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

    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename=' . $id . '.pdf');

    $pdf->Output('Order123.pdf', 'D');
}

그러나 이 요청은 저장 대화상자를 열어 pdf를 저장하는 대신 응답하고 있습니다.

%PDF-1.3 3 0 obj <> endobj 4 0 obj <> 스트림x3Rd †2D35W (r QDw3T04O30)FIS/L/lt; = #+L/lt;0 < = 0 < = #0 <0 = #0 = 0 < = #0J/T < = #개체 x x는 000000000000000000000만228000228000만5355355350000000000000000000000만0000000416 n 00000009 n 00000087 n 0000000315 n 0000000520 n 0000000595 n 트레일러 </Size 8 /Root 7 0 R /Info 6 0 R > startxref 644 %EOF

PHPExcel 라이브러리를 사용해 본 결과, 다음과 같이 동작했습니다.

$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-downloadapplication/pdf파일을 로컬에 저장하지만 다운로드 대화 상자가 표시되지 않습니다.

응답은 다음과 같습니다(Network in Chrome을 선택하면).

%PDF-1.3 3 0 obj <> endobj 4 0 obj <> 스트림x3Rd †2D35W (r QDw3T04O30)FIS/L/lt; = #+L/lt;0 < = 0 < = #0 <0 = #0 = 0 < = #0J/T < = #개체 x x는 000000000000000000000만228000228000만5355355350000000000000000000000만0000000416 n 00000009 n 00000087 n 0000000315 n 0000000520 n 0000000595 n 트레일러 </Size 8 /Root 7 0 R /Info 6 0 R > startxref 644 %EOF

갱신하다

FileSaver.js를 사용하는 방법도 동작하지 않습니다.JavaScript만으로 네이티브 Save As Dialog를 강제로 호출할 수 있는 방법은 없는 것 같습니다.Save As만 예외입니다.execCommand(IE용)execCommand SaveAs가 Firefox에서 작동하는지 확인합니다.

포함하다FileSaver.js는 프로젝트의 종속성이 됩니다.

변경합니다.downloadPDF과 같이

 $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에 대한 지원은 제한되어 있습니다.폴리필에 대해서는 https://github.com/eligrey/FileSaver.js#supported-browsers을 참조해 주세요.

「」도 합니다.Content-Disposition: attachment ★★★★★★★★★★★★★★★★★」Content-Type: application-download가 다운로드 하기 위한

여기 작업용 데모입니다.http://plnkr.co/edit/9r1tehQ94t5vkqZfZuQC?p=get, PDF에 대한 GET 요청을 표시합니다.

한 가지 제안을 드리겠습니다.

AJAX에서만 파일을 다운로드할 수 있습니다.먼저 ajax 호출을 사용하여 .zip 파일을 만들고 파일 경로를 얻은 후 임의의 명령을 사용하여 파일을 열어야 합니다.

다음으로 나에게 도움이 되는 예를 제시하겠습니다. : )

$http.post('www.abc.com/zipcreate', {'id': id}).then(function (zipurl) {
                    $window.location = zipurl;
            });

확실히, 효과가 있다.한 번 해봐.:)

편집:

또는 를 사용할 수 있습니다.

$window.location = 'abc.com/link';

in '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;

다운로드 목록에 파일이 표시됩니다.

설명서에 따르면 두 번째 파라미터는 다음과 같이 설정할 수 있습니다.D:

$pdf->Output('Order123.pdf', 'D');

저장된 파일을 사용하여 모든 세부사항을 직접 처리하고 싶다면, PHP에서 다운로드하기 위해 PDF를 브라우저에 제공하는 방법은 다음과 같습니다.

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 파일이 실제로 작성되고 있는지 확인해 주세요.웹 서버 프로세스가 해당 경로에 대한 쓰기 액세스 권한을 가지고 있습니까?FPDF f f f f f f f f f f f?으로, 「VM」이라고 하는 되었습니다.1.pdf"안녕하세요!"

<?php

require('/var/www/html/fpdf17/fpdf.php');

$_POST = array('fid' => '1');

$pdf = new FPDF();

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

$filename = '/tmp/' . $_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="' . basename($filename) . '"');

$handle = fopen($filename, 'rb');
fpassthru($handle);
fclose($handle);

unlink($filename);

?>

이치노
javascript 폼 、 javascript 폼 、 javascript 。

,,document.getElementById(formID).action= actionName

document.getElementById(formID).submit();  

여기 양식이 있습니다.이며 ID는 ID입니다.actionName 되다'/download-pdf'지정하신 대로입니다.

작업 클래스 - 응답 헤더 설정

getResponse().setContentType("application/pdf");
getResponse().setHeader("Content-Disposition",  " attachment; filename= "+"pdffile.pdf");

그러면 파일 이름 = pdfile.pdf로 파일이 다운로드됩니다.

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");
      });

 };

'보다 낫다'로 요소를 만들 도 있습니다.download★★★★

$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");
      });
 };

plnkr

이것은 (AJAX만) AJAX에서는 가능하지 않습니다.

여기서 사용할 수 있는 주요 기술은 두 가지가 있는데, 둘 JavaScript를 사용하지 않고 실제 다운로드를 수행할 수 있습니다.일반적으로 브라우저를 원하는 문서를 제공하는 리소스로 리디렉션하는 것이 일반적이며, 다운로드로 리디렉션하는 경우 해당 문서는 페이지를 벗어나지 않고 [저장] 대화상자가 표시됩니다. 질문에서도 비슷한 주제가 논의된다.

GET 요구

location.href = '/download-pdf?fid=' + encodeURIComponent($routeParams.fid);

「」를 사용하도록 스크립트를 합니다.$_GET['fid'].

POST 요구

서버는 리소스를 생성하고 리소스를 찾을 수 있는 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 응답을 반환하도록 서버 측 스크립트를 조정하십시오.

다음과 같은 방법으로 작업을 수행했는데, 제게는 잘 작동합니다.

$(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();
                    }
                });
            });
        });

내 html:

<button type="submit" class="btn btn-primary" id="generaPdf"><i class="fas fa-link"></i> Generar documento para impresión</button>

브라우저, 파일 또는 문자열과 같은 지정된 대상으로 문서를 보냅니다.브라우저의 경우 플러그인이 사용되거나(있는 경우), 다운로드("다른 이름으로 저장" 대화 상자)가 강제될 수 있습니다.

메소드는 필요에 따라 먼저 Close()를 호출하여 문서를 종료합니다.

파라미터

이름:

파일 이름지정하지 않으면 문서는 doc.pdf라는 이름으로 브라우저(대상 I)로 전송됩니다.

증류

문서를 보낼 대상입니다.다음 중 하나의 값을 사용할 수 있습니다.

  • I: 파일을 브라우저에 인라인으로 전송합니다.플러그인이 사용 가능한 경우 사용합니다.PDF를 생성하는 링크에서 "이름으로 저장" 옵션을 선택할 때 이름으로 지정된 이름이 사용됩니다.
  • D: 브라우저로 전송하여 이름으로 지정된 이름의 파일을 강제로 다운로드합니다.
  • F: 이름으로 지정된 이름으로 로컬 파일에 저장합니다(경로를 포함할 수 있습니다).
  • S: 문서를 문자열로 반환합니다.이름은 무시됩니다.

언급URL : https://stackoverflow.com/questions/30777252/download-in-browser-with-ajax-request

반응형