복붙노트

[JQUERY] 아약스 포스트에서 핸들 파일 다운로드

JQUERY

아약스 포스트에서 핸들 파일 다운로드

해결법


  1. 1.iframe을 필요가 없습니다 - 양식을 제출, 양식을 작성 POST 메소드를 사용합니다. 서버 페이지 응답이 요청에 파일의 MIME 타입에 대한 응답 헤더를 작성하고 다운로드 대화 상자를 선물 할 것이다 때 -이 여러 번 수행했습니다.

    iframe을 필요가 없습니다 - 양식을 제출, 양식을 작성 POST 메소드를 사용합니다. 서버 페이지 응답이 요청에 파일의 MIME 타입에 대한 응답 헤더를 작성하고 다운로드 대화 상자를 선물 할 것이다 때 -이 여러 번 수행했습니다.

    당신이 사용하는 어떤 언어에 대한 다운로드를 제공하는 방법을 검색 - 당신은 응용 프로그램 / 다운로드 콘텐츠 유형을 원한다.


  2. 2.이은 (최신 브라우저에서) 할 수 있기 때문에 파일 API의 부품을 사용, 이렇게 빨리 포기하지 마십시오

    이은 (최신 브라우저에서) 할 수 있기 때문에 파일 API의 부품을 사용, 이렇게 빨리 포기하지 마십시오

    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function () {
        if (this.status === 200) {
            var filename = "";
            var disposition = xhr.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('attachment') !== -1) {
                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                var matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
            }
            var type = xhr.getResponseHeader('Content-Type');
    
            var blob;
            if (typeof File === 'function') {
                try {
                    blob = new File([this.response], filename, { type: type });
                } catch (e) { /* Edge */ }
            }
            if (typeof blob === 'undefined') {
                blob = new Blob([this.response], { type: type });
            }
    
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                window.navigator.msSaveBlob(blob, filename);
            } else {
                var URL = window.URL || window.webkitURL;
                var downloadUrl = URL.createObjectURL(blob);
    
                if (filename) {
                    // use HTML5 a[download] attribute to specify filename
                    var a = document.createElement("a");
                    // safari doesn't support this yet
                    if (typeof a.download === 'undefined') {
                        window.location.href = downloadUrl;
                    } else {
                        a.href = downloadUrl;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                    }
                } else {
                    window.location.href = downloadUrl;
                }
    
                setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
            }
        }
    };
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send($.param(params));
    

    여기 jQuery.ajax를 사용하여 이전 버전입니다. 응답이 일부 캐릭터의 문자열로 변환 할 때 바이너리 데이터를 탈수 있습니다.

    $.ajax({
        type: "POST",
        url: url,
        data: params,
        success: function(response, status, xhr) {
            // check for a filename
            var filename = "";
            var disposition = xhr.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('attachment') !== -1) {
                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                var matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
            }
    
            var type = xhr.getResponseHeader('Content-Type');
            var blob = new Blob([response], { type: type });
    
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                window.navigator.msSaveBlob(blob, filename);
            } else {
                var URL = window.URL || window.webkitURL;
                var downloadUrl = URL.createObjectURL(blob);
    
                if (filename) {
                    // use HTML5 a[download] attribute to specify filename
                    var a = document.createElement("a");
                    // safari doesn't support this yet
                    if (typeof a.download === 'undefined') {
                        window.location.href = downloadUrl;
                    } else {
                        a.href = downloadUrl;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                    }
                } else {
                    window.location.href = downloadUrl;
                }
    
                setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
            }
        }
    });
    

  3. 3.저도 같은 문제에 직면하고 성공적으로 해결했다. 내 사용 사례는 이것이다.

    저도 같은 문제에 직면하고 성공적으로 해결했다. 내 사용 사례는 이것이다.

    "포스트 JSON의 서버에 데이터는 엑셀 파일을받을 수 있습니다. 그 엑셀 파일을 서버에서 생성하고 클라이언트에 대한 응답으로 반환됩니다. 브라우저에서 사용자 정의 이름을 가진 파일 "로 그 응답을 다운로드

    $("#my-button").on("click", function(){
    
    // Data to post
    data = {
        ids: [1, 2, 3, 4, 5]
    };
    
    // Use XMLHttpRequest instead of Jquery $ajax
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        var a;
        if (xhttp.readyState === 4 && xhttp.status === 200) {
            // Trick for making downloadable link
            a = document.createElement('a');
            a.href = window.URL.createObjectURL(xhttp.response);
            // Give filename you wish to download
            a.download = "test-file.xls";
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
        }
    };
    // Post data to URL which handles post request
    xhttp.open("POST", excelDownloadUrl);
    xhttp.setRequestHeader("Content-Type", "application/json");
    // You should set responseType as blob for binary responses
    xhttp.responseType = 'blob';
    xhttp.send(JSON.stringify(data));
    });
    

    위의 코드 조각은 다음을 수행한다

    여기에서 우리는 조심스럽게 서버 측에서 몇 가지를 설정해야합니다. 파이썬 장고 HttpResponse에있는 몇 가지 헤더를 설정합니다. 당신은 당신이 다른 프로그래밍 언어를 사용하는 경우 적절하게 설정해야합니다.

    # In python django code
    response = HttpResponse(file_content, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    

    나는 여기 다운로드 XLS (엑셀) 때문에, 나는 위의 하나의 contentType을 수정합니다. 당신은 당신의 파일 유형에 따라 설정해야합니다. 당신은 파일의 종류를 다운로드하려면이 기술을 사용할 수 있습니다.


  4. 4.당신은 어떤 서버 측 언어를 사용하고 있습니까? 내 응용 프로그램에서 나는 쉽게 PHP의 응답 올바른 헤더를 설정하여 AJAX 호출에서 파일을 다운로드 할 수 있습니다 :

    당신은 어떤 서버 측 언어를 사용하고 있습니까? 내 응용 프로그램에서 나는 쉽게 PHP의 응답 올바른 헤더를 설정하여 AJAX 호출에서 파일을 다운로드 할 수 있습니다 :

    header("HTTP/1.1 200 OK");
    header("Pragma: public");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    
    // The optional second 'replace' parameter indicates whether the header
    // should replace a previous similar header, or add a second header of
    // the same type. By default it will replace, but if you pass in FALSE
    // as the second argument you can force multiple headers of the same type.
    header("Cache-Control: private", false);
    
    header("Content-type: " . $mimeType);
    
    // $strFileName is, of course, the filename of the file being downloaded. 
    // This won't have to be the same name as the actual file.
    header("Content-Disposition: attachment; filename=\"{$strFileName}\""); 
    
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . mb_strlen($strFile));
    
    // $strFile is a binary representation of the file that is being downloaded.
    echo $strFile;
    

    이 의지 사실 '재 지정'이 다운로드 페이지로 브라우저하지만 @ahren 이미 그의 코멘트에 말했듯이, 그것을하지 탐색 떨어져 현재 페이지에서 것이다.

    나는 확실히 당신이 PHP 아니라면 사용하고있는 서버 측 언어에 대한 적절한 해결책을 찾을 수있어 있도록 올바른 헤더를 설정하는 방법에 대한 전부입니다.

    이미 AJAX 호출을 만드는 방법을 알고 가정하면, 클라이언트 측에서 당신은 서버에 AJAX 요청을 실행합니다. 서버는이 파일을 다운로드 할 수있는, 예를 들어,에서 링크를 생성 당신이 가리킨하려는 '앞으로'URL. 예를 들어, 서버 응답 :

    {
        status: 1, // ok
        // unique one-time download token, not required of course
        message: 'http://yourwebsite.com/getdownload/ska08912dsa'
    }
    

    응답을 처리 할 때, 당신의 몸에 iframe이 분사 당신과 당신은 그냥이 (이 예제의 편의를 위해 jQuery를 사용)와 같은 수신 된 URL에 iframe 대응의 SRC를 설정합니다 :

    $("body").append("<iframe src='" + data.message +
      "' style='display: none;' ></iframe>");
    

    위 그림과 같이 올바른 헤더를 설정 한 경우, iframe이 현재 페이지에서 멀리 브라우저를 이동하지 않고 다운로드 대화 상자를 강제 할 것이다.

    귀하의 질문과 관련하여 추가뿐만 아니라, 나는 그것이 AJAX 기술로 물건을 요청할 때 항상 JSON을 반환하는 것이 가장 좋습니다 생각합니다. 당신은 JSON 응답을받은 후에는 그것과 어떤 클라이언트 측을 결정할 수 있습니다. 어쩌면, 예를 들어, 나중에에 사용자가 현재 설정에서 직접 다운로드를 강제하는 대신 URL에 다운로드 링크를 클릭합니다 당신은 클라이언트와 서버 측이 그렇게 모두 업데이트해야합니다.


  5. 5.각도 관점에서 해결책을 찾는 사람들을 위해, 이것은 나를 위해 일한 :

    각도 관점에서 해결책을 찾는 사람들을 위해, 이것은 나를 위해 일한 :

    $http.post(
      'url',
      {},
      {responseType: 'arraybuffer'}
    ).then(function (response) {
      var headers = response.headers();
      var blob = new Blob([response.data],{type:headers['content-type']});
      var link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = "Filename";
      link.click();
    });
    

  6. 6.여기에 내가이 작업을 가지고 어떻게 https://stackoverflow.com/a/27563953/2845977

    여기에 내가이 작업을 가지고 어떻게 https://stackoverflow.com/a/27563953/2845977

    {(아약스 $ URL : '', 성공 : 기능 (데이터) { VAR의 새로운 블롭이 블롭 = ([데이터]); VAR 링크 = document.createElement ( 'A'); link.href = window.URL.createObjectURL (BLOB); link.download = ""; () link.click; } });

    {(아약스 $ URL : '', 성공 : download.bind (사실, "", "") });


  7. 7.나는 그러나 난 그냥 큰 POST 요청과 같은 일을 달성하려고하는 사람을 도울 수있는 몇 가지 정보를 추가하고 싶어, 당신은 이미 해결책을 발견했습니다 참조하십시오.

    나는 그러나 난 그냥 큰 POST 요청과 같은 일을 달성하려고하는 사람을 도울 수있는 몇 가지 정보를 추가하고 싶어, 당신은 이미 해결책을 발견했습니다 참조하십시오.

    나는 실제로는 AJAX를 통해 "깨끗한"다운로드를 달성 할 수없는, 몇 주 전에 동일한 문제가 있었다, 필라멘트 그룹 정확하게 당신이 이미 발견 한 방법이라고 jQuery를 파일을 작동하는 jQuery 플러그인을 작성 다운로드 그러나이 기술에 단점이있다.

    당신이 AJAX를 통해 (예를 들어 파일 + 1MB의) 큰 요청을 보내는 경우는 충격 응답 부정적인 것이다. 느린 인터넷 연결에서 당신은 요청이 전송 될 때까지 많이 기다려 또한 다운로드 파일 기다려야 할 것이다. 그것은하지 즉시처럼 => "팝업"=> "다운로드 시작"을 "클릭"합니다. 그것은 더 당신이 요청이 전송 될 때까지 대기해야하기 때문에 파일의 크기를 두 배로 보이게 => "다운로드 시작", "데이터가 전송 될 때까지 대기"=> "를 클릭"=> "응답 대기"처럼 AJAX 통해 다운로드 할 수있는 파일로 다시 얻을.

    당신이 작은 파일 크기로 작업하는 경우 <1메가바이트 당신은이 통지하지 않습니다. 난 내 자신의 응용 프로그램에서 발견하지만, 더 큰 파일 크기에 거의 참을 수 있습니다.

    내 애플 수출 이미지에 사용자가 동적으로, 이러한 이미지는 서버 (이 유일하게 가능한 방법입니다)에 64 기수 형식으로 POST 요청을 통해 전송됩니다 생성 할 수 후 처리, .JPG의 .png 파일의 형태로 사용자에게 다시 전송, base64로 1메가바이트 + 이미지 문자열은 파일 다운로드를 시작하기 위해 필요 이상 기다릴 큰,이 힘은 사용자입니다. 느린 인터넷 연결에서 정말 짜증나는 일 수있다.

    이것에 대한 내 솔루션이 준비되면, 동적으로 "기다려주십시오 ..."사이에 변경하는 버튼의 형태로 파일에 대한 링크를 생성하고 "다운로드"주와 같은에서 일시적으로 쓰기로 서버에 파일이었다 "마우스 오른쪽 버튼으로 클릭"사용자가 할 수 있도록하고 저장 시간, 미리보기 팝업 창에서 base64로 이미지를 인쇄 할 수 있습니다. 이 사용자에 대한 모든 대기 시간이 더 견딜 수, 또한 속도 일까지.

    업데이트 2014년 9월 30일 :

    스크립트 예제를 다운로드 :

    <?php
    // Record ID
    $downloadID = (int)$_POST['id'];
    // Query Data (this example uses CodeIgniter)
    $data       = $CI->MyQueries->GetDownload( $downloadID );
    // base64 tags are replaced by [removed], so we strip them out
    $base64     = base64_decode( preg_replace('#\[removed\]#', '', $data[0]->image) );
    // This example is for base64 images
    $imgsize    = getimagesize( $base64 );
    // Set content headers
    header('Content-Disposition: attachment; filename="my-file.png"');
    header('Content-type: '.$imgsize['mime']);
    // Force download
    echo $base64;
    ?>
    

    그러나 나는 내가 내 연구 결과와 함께 내 대답을 업데이트하는 것이 좋을 것입니다 생각, 이것은 OP는 질문 것 이상의 방법을 알고있다. 나는 내 문제에 대한 해결책을 검색 할 때, 나는 나에게 내가 찾던 답을주지 않았다 스레드 "AJAX POST 데이터에서 다운로드"많이 읽고,이 정보가 이런 식으로 뭔가를 달성하고자하는 사람을 도움이되기를 바랍니다.


  8. 8.나는 즉 양식 게시물을 사용, 허용 대답에이 기술을 사용할 때 발생하는 어려움을 지적 할 :

    나는 즉 양식 게시물을 사용, 허용 대답에이 기술을 사용할 때 발생하는 어려움을 지적 할 :

    나는 S3에 파일을 저장하고 파일을 얻을 수있는 사전 서명 된 URL을 전송하는 방법을 사용하여 끝났다.


  9. 9.여기에 임시 숨겨진 양식을 사용하여 내 솔루션입니다.

    여기에 임시 숨겨진 양식을 사용하여 내 솔루션입니다.

    //Create an hidden form
    var form = $('<form>', {'method': 'POST', 'action': this.href}).hide();
    
    //Add params
    var params = { ...your params... };
    $.each(params, function (k, v) {
        form.append($('<input>', {'type': 'hidden', 'name': k, 'value': v}));
    });
    
    //Make it part of the document and submit
    $('body').append(form);
    form.submit();
    
    //Clean up
    form.remove();
    

    참고 내가 대규모 JQuery와 사용하지만 기본 JS와 동일한 기능을 수행 할 수있다.


  10. 10.좀 더 현대적인 접근 방법을 찾고있는 사람들을 위해, 당신은이 API를 가져올 수 있습니다. 다음 예제 프로그램에서는 스프레드 시트 파일을 다운로드합니다. 그것은 쉽게 다음 코드로 이루어집니다.

    좀 더 현대적인 접근 방법을 찾고있는 사람들을 위해, 당신은이 API를 가져올 수 있습니다. 다음 예제 프로그램에서는 스프레드 시트 파일을 다운로드합니다. 그것은 쉽게 다음 코드로 이루어집니다.

    fetch(url, {
        body: JSON.stringify(data),
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        },
    })
    .then(response => response.blob())
    .then(response => {
        const blob = new Blob([response], {type: 'application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        const downloadUrl = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "file.xlsx";
        document.body.appendChild(a);
        a.click();
    })
    

    나는이 방법은 다른 XMLHttpRequest의 솔루션보다 훨씬 쉽게 이해할 수 믿습니다. 또한, 추가 라이브러리를 추가 할 필요없이, JQuery와 접근 방식과 유사한 구문을 가지고있다.

    물론, 당신이 새로운 접근 방식 때문에, 개발하고있는 브라우저 IE에서 작동을하지 않습니다 확인 권합니다. 다음 [링크]의 전체 브라우저 호환성 목록 [1]을 찾을 수 있습니다.

    중요 :이 예에서 나는 지정된 URL의 서버 듣기에 JSON 요청을 전송하고 있습니다. 이 URL은 내 예에 나는 당신이이 부분을 알고 가정하고, 설정해야합니다. 또한, 작업에 대한 귀하의 요청에 필요한 헤더를 고려한다. 내가 JSON을 보내고 있기 때문에, 나는 Content-Type 헤더를 추가하고 응용 프로그램 / JSON으로 설정해야합니다; 문자셋 = UTF-8, 서버가 수신 할 요청의 유형을 알 수 있도록한다.


  11. 11.다른 사람이 언급했듯이, 당신은 생성하고 POST 요청을 통해 다운로드 할 수있는 양식을 제출할 수 있습니다. 그러나이 수동으로 할 필요가 없습니다.

    다른 사람이 언급했듯이, 당신은 생성하고 POST 요청을 통해 다운로드 할 수있는 양식을 제출할 수 있습니다. 그러나이 수동으로 할 필요가 없습니다.

    일에 대한 하나의 정말 간단한 라이브러리는 정확히이 jquery.redirect입니다. 이것은 표준 jQuery.post 방법과 유사한 API를 제공한다 :

    $.redirect(url, [values, [method, [target]]])
    

  12. 12.이것은 3 세 질문이지만 오늘 같은 문제가 있었다. 나는 당신의 편집 솔루션을 보았다하지만 난 그게 이중 요청을하기 때문에 그 성능을 희생 할 수 있다고 생각합니다. 사람이 두 번 다음 서비스를 호출하는 의미하지 않는 다른 솔루션을 필요 그렇다면이 내가했던 방법입니다 :

    이것은 3 세 질문이지만 오늘 같은 문제가 있었다. 나는 당신의 편집 솔루션을 보았다하지만 난 그게 이중 요청을하기 때문에 그 성능을 희생 할 수 있다고 생각합니다. 사람이 두 번 다음 서비스를 호출하는 의미하지 않는 다른 솔루션을 필요 그렇다면이 내가했던 방법입니다 :

    <form id="export-csv-form" method="POST" action="/the/path/to/file">
        <input type="hidden" name="anyValueToPassTheServer" value="">
    </form>
    

    이 양식은 바로 서비스를 호출하고에서는 window.location을 사용하지 않도록하는 데 사용됩니다 (). 당신은 단지 형태가 서비스를 호출하고 파일을 얻기 위해 JQuery와에서 제출 확인해야합니다 그 후. 그것은 아주 간단하지만,이 방법은 당신이 POST를 사용하여 다운로드 할 수 있습니다. 지금은이 서비스 당신이있는 거 호출이 GET 인 경우 쉽게 될 수 있지만, 내 경우는 아니다.


  13. 13.나는이 FileSaver.js을 사용했다. CSV 파일 내 경우에는 내가 (커피 스크립트에) 이런 짓을 :

    나는이 FileSaver.js을 사용했다. CSV 파일 내 경우에는 내가 (커피 스크립트에) 이런 짓을 :

      $.ajax
        url: "url-to-server"
        data: "data-to-send"
        success: (csvData)->
          blob = new Blob([csvData], { type: 'text/csv' })
          saveAs(blob, "filename.csv")
    

    내가 가장 복잡한 경우에, 데이터가 적절히 처리해야합니다 생각합니다. 후드 FileSaver.js는 조나단의 답변을 개정에게 동일한 접근 방식을 구현한다.


  14. 14.참조 : http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/ 그 다음 filesaver에 투입 할 수있는 응답과 같은 덩어리를 돌아갑니다

    참조 : http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/ 그 다음 filesaver에 투입 할 수있는 응답과 같은 덩어리를 돌아갑니다


  15. 15.가장자리에있는 일에 조나단 보상의 답을 얻기 위해 나는 다음과 같이 변경했다 :

    가장자리에있는 일에 조나단 보상의 답을 얻기 위해 나는 다음과 같이 변경했다 :

    var blob = typeof File === 'function'
        ? new File([this.response], filename, { type: type })
        : new Blob([this.response], { type: type });
    

    이에

    var f = typeof File+"";
    var blob = f === 'function' && Modernizr.fileapi
        ? new File([this.response], filename, { type: type })
        : new Blob([this.response], { type: type });
    

    차라리 주석으로이 게시 한 것입니다하지만 난 그것에 대해 충분히 명성을 가지고 있지 않습니다


  16. 16.다음은 서로 다른 소스에서 수집 한 내 솔루션입니다 : 서버 측 구현 :

    다음은 서로 다른 소스에서 수집 한 내 솔루션입니다 : 서버 측 구현 :

        String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        // Set headers
        response.setHeader("content-disposition", "attachment; filename =" + fileName);
        response.setContentType(contentType);
        // Copy file to output stream
        ServletOutputStream servletOutputStream = response.getOutputStream();
        try (InputStream inputStream = new FileInputStream(file)) {
            IOUtils.copy(inputStream, servletOutputStream);
        } finally {
            servletOutputStream.flush();
            Utils.closeQuitely(servletOutputStream);
            fileToDownload = null;
        }
    

    클라이언트 측 구현 (jQuery를 사용) :

    $.ajax({
    type: 'POST',
    contentType: 'application/json',
        url: <download file url>,
        data: JSON.stringify(postObject),
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        },
        success: function(message, textStatus, response) {
           var header = response.getResponseHeader('Content-Disposition');
           var fileName = header.split("=")[1];
           var blob = new Blob([message]);
           var link = document.createElement('a');
           link.href = window.URL.createObjectURL(blob);
           link.download = fileName;
           link.click();
        }
    });   
    

  17. 17.아약스에서 웹 페이지를 다운로드 할 수있는 다른 해결책이있다. 하지만 먼저 처리 한 후 다운로드해야 페이지를 참조하고있다.

    아약스에서 웹 페이지를 다운로드 할 수있는 다른 해결책이있다. 하지만 먼저 처리 한 후 다운로드해야 페이지를 참조하고있다.

    먼저 결과 다운로드에서 페이지 처리를 분리해야합니다.

    1) 만 페이지 계산은 아약스 호출에서 만들어집니다.

    $.post("CalculusPage.php", { calculusFunction: true, ID: 29, data1: "a", data2: "b" },
    
           function(data, status) 
           {
                if (status == "success") 
                {
                    /* 2) In the answer the page that uses the previous calculations is downloaded. For example, this can be a page that prints the results of a table calculated in the ajax call. */
                    window.location.href = DownloadPage.php+"?ID="+29;
                }               
           }
    );
    
    // For example: in the CalculusPage.php
    
        if ( !empty($_POST["calculusFunction"]) ) 
        {
            $ID = $_POST["ID"];
    
            $query = "INSERT INTO ExamplePage (data1, data2) VALUES ('".$_POST["data1"]."', '".$_POST["data2"]."') WHERE id = ".$ID;
            ...
        }
    
    // For example: in the DownloadPage.php
    
        $ID = $_GET["ID"];
    
        $sede = "SELECT * FROM ExamplePage WHERE id = ".$ID;
        ...
    
        $filename="Export_Data.xls";
        header("Content-Type: application/vnd.ms-excel");
        header("Content-Disposition: inline; filename=$filename");
    
        ...
    

    나는 그것이 나를 위해이었다 용액으로, 많은 도움이 될 수 있기를 바랍니다.


  18. 18.응답이 배열 버퍼의 경우, 아약스에서 onsuccess는 이벤트에서이 시도 :

    응답이 배열 버퍼의 경우, 아약스에서 onsuccess는 이벤트에서이 시도 :

     if (event.data instanceof ArrayBuffer) {
              var binary = '';
              var bytes = new Uint8Array(event.data);
              for (var i = 0; i < bytes.byteLength; i++) {
                  binary += String.fromCharCode(bytes[i])
              }
              $("#some_id").append("<li><img src=\"data:image/png;base64," + window.btoa(binary) + "\"/></span></li>");
              return;
          }
    

  19. 19.아래는 여러 파일 일부 식별자로 구성되어 일부 목록에 따라 데이터베이스에서 찾고 다운로드 내 솔루션이며, 파일이 결정됩니다 다운로드 준비 - 그 존재하는 경우. 나는 Ajax를 사용하여 각 파일에 대한 C # MVC 액션을 호출하고있다.

    아래는 여러 파일 일부 식별자로 구성되어 일부 목록에 따라 데이터베이스에서 찾고 다운로드 내 솔루션이며, 파일이 결정됩니다 다운로드 준비 - 그 존재하는 경우. 나는 Ajax를 사용하여 각 파일에 대한 C # MVC 액션을 호출하고있다.

    다른 사람이 말한 것처럼 그리고 예, jQuery를 아약스에서 할 수 있습니다. 나는 아약스의 성공을했고, 나는 항상 응답 (200)을 전송하고 있습니다.

    그래서,이 키는 다음과 같습니다

      success: function (data, textStatus, xhr) {
    

    그리고 이것은 내 코드는 다음과 같습니다

    var i = 0;
    var max = 0;
    function DownloadMultipleFiles() {
                if ($(".dataTables_scrollBody>tr.selected").length > 0) {
                    var list = [];
                    showPreloader();
                    $(".dataTables_scrollBody>tr.selected").each(function (e) {
                        var element = $(this);
                        var orderid = element.data("orderid");
                        var iscustom = element.data("iscustom");
                        var orderlineid = element.data("orderlineid");
                        var folderPath = "";
                        var fileName = "";
    
                        list.push({ orderId: orderid, isCustomOrderLine: iscustom, orderLineId: orderlineid, folderPath: folderPath, fileName: fileName });
                    });
                    i = 0;
                    max = list.length;
                    DownloadFile(list);
                }
            }
    

    그리고 전화 :

    function DownloadFile(list) {
            $.ajax({
                url: '@Url.Action("OpenFile","OrderLines")',
                type: "post",
                data: list[i],
                xhrFields: {
                    responseType: 'blob'
                },
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("RequestVerificationToken",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
    
                },
                success: function (data, textStatus, xhr) {
                    // check for a filename
                    var filename = "";
                    var disposition = xhr.getResponseHeader('Content-Disposition');
                    if (disposition && disposition.indexOf('attachment') !== -1) {
                        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                        var matches = filenameRegex.exec(disposition);
                        if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                        var a = document.createElement('a');
                        var url = window.URL.createObjectURL(data);
                        a.href = url;
                        a.download = filename;
                        document.body.append(a);
                        a.click();
                        a.remove();
                        window.URL.revokeObjectURL(url);
                    }
                    else {
                        getErrorToastMessage("Production file for order line " + list[i].orderLineId + " does not exist");
                    }
                    i = i + 1;
                    if (i < max) {
                        DownloadFile(list);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
    
                },
                complete: function () {
                    if(i===max)
                    hidePreloader();
                }
            });
        }
    

    C # MVC :

     [HttpPost]
     [ValidateAntiForgeryToken]
    public IActionResult OpenFile(OrderLineSimpleModel model)
            {
                byte[] file = null;
    
                try
                {
                    if (model != null)
                    {
                        //code for getting file from api - part is missing here as not important for this example
                        file = apiHandler.Get<byte[]>(downloadApiUrl, token);
    
                        var contentDispositionHeader = new System.Net.Mime.ContentDisposition
                        {
                            Inline = true,
                            FileName = fileName
                        };
                        //    Response.Headers.Add("Content-Disposition", contentDispositionHeader.ToString() + "; attachment");
                        Response.Headers.Add("Content-Type", "application/pdf");
                        Response.Headers.Add("Content-Disposition", "attachment; filename=" + fileName);
                        Response.Headers.Add("Content-Transfer-Encoding", "binary");
                        Response.Headers.Add("Content-Length", file.Length.ToString());
    
                    }
                }
                catch (Exception ex)
                {
                    this.logger.LogError(ex, "Error getting pdf", null);
                    return Ok();
                }
    
                return File(file, System.Net.Mime.MediaTypeNames.Application.Pdf);
            }
    

    만큼 당신이 응답 (200)를 반환으로, 아약스에서의 성공은 파일이 실제로이 경우 아래의 라인이 거짓이 될 것 같은 존재 여부를 여부를 확인할 수 있습니다, 함께 작업 할 수 있습니다 그리고 당신은 그것에 대해 사용자에게 알릴 수있다 :

     if (disposition && disposition.indexOf('attachment') !== -1) {
    

  20. 20.나는 @ 알랭 - 크루즈의 것과 유사한 솔루션을 필요로하지만, 다수의 다운로드와 nuxt / VUE있다. 나는 브라우저가 여러 파일 다운로드를 차단 알고, 나 또한 data.I 형식의 CSV 세트 처음에 JSZip를 사용하려고했지만, 난 지금 여기에 IE의 지원이 필요 내 솔루션입니다 반환 API가 있습니다. 사람이 도움을 줄 수 있다면 나에게 좋은 것 그이 향상하지만, 지금까지 나를 위해 일하고있다.

    나는 @ 알랭 - 크루즈의 것과 유사한 솔루션을 필요로하지만, 다수의 다운로드와 nuxt / VUE있다. 나는 브라우저가 여러 파일 다운로드를 차단 알고, 나 또한 data.I 형식의 CSV 세트 처음에 JSZip를 사용하려고했지만, 난 지금 여기에 IE의 지원이 필요 내 솔루션입니다 반환 API가 있습니다. 사람이 도움을 줄 수 있다면 나에게 좋은 것 그이 향상하지만, 지금까지 나를 위해 일하고있다.

    API 반환 :

    data : {
      body: {
        fileOne: ""col1", "col2", "datarow1.1", "datarow1.2"...so on",
        fileTwo: ""col1", "col2"..."
      }
    }
    

    page.vue :

    <template>
      <b-link @click.prevent="handleFileExport">Export<b-link>
    </template>
    
    export default = {
       data() {
         return {
           fileNames: ['fileOne', 'fileTwo'],
         }
       },
      computed: {
        ...mapState({
           fileOne: (state) => state.exportFile.fileOne,
           fileTwo: (state) => state.exportFile.fileTwo,
        }),
      },
      method: {
        handleExport() {
          //exportFileAction in store/exportFile needs to return promise
          this.$store.dispatch('exportFile/exportFileAction', paramsToSend)
            .then(async (response) => {
               const downloadPrep = this.fileNames.map(async (fileName) => {
               // using lodash to get computed data by the file name
               const currentData = await _.get(this, `${fileName}`);
               const currentFileName = fileName;
               return { currentData, currentFileName };
             });
             const response = await Promise.all(downloadPrep);
             return response;
           })
           .then(async (data) => {
             data.forEach(({ currentData, currentFileName }) => {
               this.forceFileDownload(currentData, currentFileName);
             });
           })
           .catch(console.error);
        },
        forceFileDownload(data, fileName) {
         const url = window.URL
             .createObjectURL(new Blob([data], { type: 'text/csv;charset=utf-8;' }));
         const link = document.createElement('a');
         link.href = url;
         link.setAttribute('download', `${fileName}.csv`);
         document.body.appendChild(link);
         link.click();
       },
    }
    
  21. from https://stackoverflow.com/questions/16086162/handle-file-download-from-ajax-post by cc-by-sa and MIT license