programing

ajax call php를 통해 파일 다운로드

starjava 2023. 2. 21. 23:18
반응형

ajax call php를 통해 파일 다운로드

단추가 있고onclickAjax 함수를 호출합니다.

여기 아약스 기능이 있습니다.

function csv(){

    ajaxRequest = ajax();//ajax() is function that has all the XML HTTP Requests

    postdata = "data=" + document.getElementById("id").value;

    ajaxRequest.onreadystatechange = function(){
        var ajaxDisplay = document.getElementById('ajaxDiv');
        if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
            ajaxDisplay.innerHTML = ajaxRequest.responseText;           
        }
    }

    ajaxRequest.open("POST","csv.php",false);
    ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajaxRequest.send(postdata);
}

사용자 입력에 따라 csv 파일을 만듭니다.작성 후 다운로드 프롬프트 또는 강제 다운로드(가능하면 강제 실행)하도록 하겠습니다.php 파일 끝에 있는 다음 스크립트를 사용하여 파일을 다운로드합니다.이 스크립트를 다른 파일로 실행하면 정상적으로 동작합니다.

$fileName = 'file.csv';
$downloadFileName = 'newfile.csv';

if (file_exists($fileName)) {
    header('Content-Description: File Transfer');
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename='.$downloadFileName);
    ob_clean();
    flush();
    readfile($fileName);
    exit;
}
echo "done";

단, csv.php의 마지막에 실행하면 다운로드가 아닌 file.csv의 내용이 페이지(ajaxDiv로)로 출력됩니다.

csv.php 말미에 파일을 강제로 다운로드하는 방법이 있나요?

AJAX는 파일 다운로드용이 아닙니다.다운로드 링크를 주소로 하는 새 창을 띄우거나document.location = ....

jQuery를 사용한 매우 간단한 솔루션:

클라이언트 측:

$('.act_download_statement').click(function(e){
    e.preventDefault();
    form = $('#my_form');
    form.submit();
});

서버측에서는, 반드시 올바른 것을 반송해 주세요.Content-Type이 경우 브라우저가 첨부 파일을 인식하고 다운로드가 시작됩니다.

@joe: 감사합니다, 좋은 경고였습니다!

조금 더 어려운 문제가 있었습니다.1. 서버에서 ZIP 파일을 생성하기 위한 POST 데이터 첨부 AJAX 요청 보내기 2. 응답 받기 3. ZIP 파일을 다운로드하기

그렇게 했습니다(JQuery를 사용하여 AJAX 요청을 처리).

  1. 최초 투고 요청:

    var parameters = {
         pid     : "mypid",
       "files[]": ["file1.jpg","file2.jpg","file3.jpg"]
    }

    var options = { url: "request/url",//replace with your request url type: "POST",//replace with your request type data: parameters,//see above context: document.body,//replace with your contex success: function(data){ if (data) { if (data.path) { //Create an hidden iframe, with the 'src' attribute set to the created ZIP file. var dlif = $('<iframe/>',{'src':data.path}).hide(); //Append the iFrame to the context this.append(dlif); } else if (data.error) { alert(data.error); } else { alert('Something went wrong'); } } } }; $.ajax(options);

"request/url"은 zip 작성(토픽을 벗어남)을 처리하고 다음 JSON 개체를 반환합니다.예를 들어 다음과 같습니다.

 //Code to create the zip file
 //......
 //Id of the file
 $zipid = "myzipfile.zip"
 //Download Link - it can be prettier
 $dlink = 'http://'.$_SERVER["SERVER_NAME"].'/request/download&file='.$zipid;
 //JSON response to be handled on the client side
 $result = '{"success":1,"path":"'.$dlink.'","error":null}';
 header('Content-type: application/json;');
 echo $result;

"request/download"는 필요에 따라 몇 가지 보안 검사를 수행하고 파일 전송을 생성할 수 있습니다.

$fn = $_GET['file'];
if ($fn) {
  //Perform security checks
  //.....check user session/role/whatever
  $result = $_SERVER['DOCUMENT_ROOT'].'/path/to/file/'.$fn;
  if (file_exists($result)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/force-download');
    header('Content-Disposition: attachment; filename='.basename($result));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($result));
    ob_clean();
    flush();
    readfile($result);
    @unlink($result);
  }

}

나는 이것을 숨겨진 iframe으로 해냈다.php가 아닌 perl을 사용하므로 코드 솔루션이 아닌 개념만 제공합니다.

클라이언트가 Ajax 요청을 서버로 전송하여 파일 내용이 생성됩니다.이 파일은 서버에 임시 파일로 저장되며 파일 이름이 클라이언트에 반환됩니다.

클라이언트(javascript)는 파일명을 수신하고 iframe src를 다음과 같이 파일을 전달하는 URL로 설정합니다.

$('iframe_dl').src="/app?download=1&filename=" + the_filename

서버는 파일을 슬러핑하여 링크를 해제하고 다음 헤더를 포함한 스트림을 클라이언트에 전송합니다.

Content-Type:'application/force-download'
Content-Disposition:'attachment; filename=the_filename'

마법처럼 작동한다.

Ajax를 통해 직접 파일을 다운로드할 수 없습니다.

페이지에 URL을 포함한 링크를 파일(ajax 콜에서 반환됨)에 붙이거나 숨김을 사용하는 다른 방법을 사용할 수 있습니다.iframe URL 의 을 합니다.iframe 페이지를 고치지 않고 할 수 .이렇게 하면 페이지를 새로 고치지 않고 파일을 다운로드할 수 있습니다.

여기 코드가 있습니다.

$.ajax({
    url : "yourURL.php",
    type : "GET",
    success : function(data) {
        $("#iframeID").attr('src', 'downloadFileURL');
    }
});

다음과 같이 할 수 있습니다.

PHP REST API: (백엔드)

header('Content-Description:File Transfer');
header('Content-Type:application/octet-stream');
header('Content-Disposition:attachment; filename=' . $toBeDownloaded);
header('Content-Transfer-Encoding:binary');
header('Expires:0');
header('Cache-Control:must-revalidate');
header('Pragma:public');
header('Content-Length:'.filesize($toBeDownloaded));
readfile($toBeDownloaded);
exit;

자바스크립트 코드: (FRONTEND)

const REQUEST = `API_PATH`;
try {
  
  const response = await fetch(REQUEST, {
    method: 'GET',
  })

  const fileUploaded = await response.blob();
  const url = window.URL.createObjectURL(fileUploaded);
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', 'YOUR_FILE_NAME_WITH_EXTENSION');
  document.body.appendChild(link);
  link.click();
} catch (error) {
  console.log(error)
}

언급URL : https://stackoverflow.com/questions/6668776/download-file-through-an-ajax-call-php

반응형