복붙노트

[JQUERY] Ajax를 사용하여 다운로드 및 열려있는 PDF 파일

JQUERY

Ajax를 사용하여 다운로드 및 열려있는 PDF 파일

해결법


  1. 1.당신은 반드시 이것을 위해 Ajax를 필요가 없습니다. 서버 측 코드에서 첨부 파일 내용 - 처리를 설정하면 그냥 링크는 충분하다. 즉 당신의 주요 관심사 인 경우이 방법은 상위 페이지는 열려있을 것입니다 (당신이 불필요하게 다른이를 위해 Ajax를 선택한 이유는?). 게다가, 잘 acynchronously이 문제를 해결할 수있는 방법은 없습니다. PDF는 문자 데이터가 아닙니다. 그것은 바이너리 데이터를합니다. 당신은 $ (요소) .load 같은 물건을 할 수 없습니다 (). 당신은 이것에 대한 완전히 새로운 요청을 사용하고 싶습니다. 그 PDF 를 위해 완벽하게 적합합니다.

    당신은 반드시 이것을 위해 Ajax를 필요가 없습니다. 서버 측 코드에서 첨부 파일 내용 - 처리를 설정하면 그냥 링크는 충분하다. 즉 당신의 주요 관심사 인 경우이 방법은 상위 페이지는 열려있을 것입니다 (당신이 불필요하게 다른이를 위해 Ajax를 선택한 이유는?). 게다가, 잘 acynchronously이 문제를 해결할 수있는 방법은 없습니다. PDF는 문자 데이터가 아닙니다. 그것은 바이너리 데이터를합니다. 당신은 $ (요소) .load 같은 물건을 할 수 없습니다 (). 당신은 이것에 대한 완전히 새로운 요청을 사용하고 싶습니다. 그 PDF 를 위해 완벽하게 적합합니다.

    당신은 서버 측 코드와 더 많은 지원하기 위해, 당신은 더 많은 사용되는 언어에 대한 이야기와 코드 시도의 발췌를 게시해야합니다.


  2. 2.여기에 내가이 작업을 가지고 어떻게

    여기에 내가이 작업을 가지고 어떻게

    {(아약스 $ URL : '', 성공 : 기능 (데이터) { VAR의 새로운 블롭이 블롭 = ([데이터]); VAR 링크 = document.createElement ( 'A'); link.href = window.URL.createObjectURL (BLOB); link.download = ""; () link.click; } }); <스크립트 SRC = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

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


  3. 3.정말 과거 대답 중 하나가 원래 포스터의 문제를 발견 생각하지 않습니다. 포스터는 POST 데이터를 시도하고 응답 다운로드를 얻을 동안 그들은 모두 GET 요청을 추정한다.

    정말 과거 대답 중 하나가 원래 포스터의 문제를 발견 생각하지 않습니다. 포스터는 POST 데이터를 시도하고 응답 다운로드를 얻을 동안 그들은 모두 GET 요청을 추정한다.

    더 나은 응답에 대한 검색의 과정에서 우리는 파일 다운로드 아약스와 같은 요청이 jQuery를 플러그인을 발견했다.

    그 "마음"그것은 입력 필드로 주어진 데이터를 포함하는 "일시적으로"HTML 양식을 만듭니다. 이 양식은 문서에 추가하고 원하는 URL에 게시됩니다. 오른쪽 양식이 다시 제거되었는지 후 :

    jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
        .appendTo('body').submit().remove()
    

    업데이트 Mayur의 응답 외모 꽤 유망 내가 언급 플러그인으로 jQuery를에 비해 매우 간단합니다.


  4. 4.이것은 내가이 문제를 해결하는 방법입니다. 이 게시물에 개정 조나단의 대답은 나에게 많은 도움이되었습니다. 다음의 예는 단순화된다.

    이것은 내가이 문제를 해결하는 방법입니다. 이 게시물에 개정 조나단의 대답은 나에게 많은 도움이되었습니다. 다음의 예는 단순화된다.

    자세한 내용은 위의 소스 코드는 JQuery와 아약스 요청 (등 GET, POST, PUT)을 사용하여 파일을 다운로드 할 수 있습니다. 그것은 또한, JSON으로 매개 변수를 업로드하고 응용 프로그램 / JSON (내 기본값)에 콘텐츠 형식을 변경하는 데 도움이됩니다.

    HTML 소스 :

    <form method="POST">
        <input type="text" name="startDate"/>
        <input type="text" name="endDate"/>
        <input type="text" name="startDate"/>
        <select name="reportTimeDetail">
            <option value="1">1</option>
        </select>
        <button type="submit"> Submit</button>
    </form>  
    

    두 입력 텍스트 간단한 형태는, 하나의 선택 버튼 소자.

    자바 스크립트 페이지 소스 :

    <script type="text/javascript" src="JQuery 1.11.0 link"></script>
    <script type="text/javascript">
        // File Download on form submition.
        $(document).on("ready", function(){
            $("form button").on("click", function (event) {
                event.stopPropagation(); // Do not propagate the event.
    
                // Create an object that will manage to download the file.
                new AjaxDownloadFile({
                    url: "url that returns a file",
                    data: JSON.stringify($("form").serializeObject())
                });
    
                return false; // Do not submit the form.
            });
        });
    </script>  
    

    버튼 클릭에 대한 간단한 이벤트입니다. 그것은 AjaxDownloadFile 개체를 만듭니다. AjaxDownloadFile 클래스의 소스는 다음과 같습니다.

    AjaxDownloadFile 클래스 소스 :

    var AjaxDownloadFile = function (configurationSettings) {
        // Standard settings.
        this.settings = {
            // JQuery AJAX default attributes.
            url: "",
            type: "POST",
            headers: {
                "Content-Type": "application/json; charset=UTF-8"
            },
            data: {},
            // Custom events.
            onSuccessStart: function (response, status, xhr, self) {
            },
            onSuccessFinish: function (response, status, xhr, self, filename) {
            },
            onErrorOccured: function (response, status, xhr, self) {
            }
        };
        this.download = function () {
            var self = this;
            $.ajax({
                type: this.settings.type,
                url: this.settings.url,
                headers: this.settings.headers,
                data: this.settings.data,
                success: function (response, status, xhr) {
                    // Start custom event.
                    self.settings.onSuccessStart(response, status, xhr, self);
    
                    // Check if a filename is existing on the response headers.
                    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 = downloadUrl;
                            } else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.click();
                            }
                        } else {
                            window.location = downloadUrl;
                        }
    
                        setTimeout(function () {
                            URL.revokeObjectURL(downloadUrl);
                        }, 100); // Cleanup
                    }
    
                    // Final custom event.
                    self.settings.onSuccessFinish(response, status, xhr, self, filename);
                },
                error: function (response, status, xhr) {
                    // Custom event to handle the error.
                    self.settings.onErrorOccured(response, status, xhr, self);
                }
            });
        };
        // Constructor.
        {
            // Merge settings.
            $.extend(this.settings, configurationSettings);
            // Make the request.
            this.download();
        }
    };
    

    내 JS 라이브러리에 추가로이 클래스를 만들었습니다. 그것은 다시 사용할 수 있습니다. 희망이 도움이.


  5. 5.무엇 나를 위해 일한 것은, 다음 코드 서버 기능 (memoryStream.GetBuffer (), "응용 프로그램 / PDF", "fileName.pdf을") 파일을 검색하는 것처럼 ;:

    무엇 나를 위해 일한 것은, 다음 코드 서버 기능 (memoryStream.GetBuffer (), "응용 프로그램 / PDF", "fileName.pdf을") 파일을 검색하는 것처럼 ;:

    $http.get( fullUrl, { responseType: 'arraybuffer' })
                .success(function (response) {
                    var blob = new Blob([response], { type: 'application/pdf' });
    
                    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                        window.navigator.msSaveOrOpenBlob(blob); // for IE
                    }
                    else {
                        var fileURL = URL.createObjectURL(blob);
                        var newWin = window.open(fileURL);
                        newWin.focus();
                        newWin.reload();
                    }
    });
    

  6. 6.그런 다음 페이지에서 제거, 양식을 작성하고 제출이 플러그인을 사용할 수 있습니다.

    그런 다음 페이지에서 제거, 양식을 작성하고 제출이 플러그인을 사용할 수 있습니다.

    jQuery.download = function(url, data, method) {
        //url and data options required
        if (url && data) {
            //data can be string of parameters or array/object
            data = typeof data == 'string' ? data : jQuery.param(data);
            //split params into form inputs
            var inputs = '';
            jQuery.each(data.split('&'), function() {
                var pair = this.split('=');
                inputs += '<input type="hidden" name="' + pair[0] +
                    '" value="' + pair[1] + '" />';
            });
            //send request
            jQuery('<form action="' + url +
                    '" method="' + (method || 'post') + '">' + inputs + '</form>')
                .appendTo('body').submit().remove();
        };
    };
    
    
    $.download(
        '/export.php',
        'filename=mySpreadsheet&format=xls&content=' + spreadsheetData
    );
    

    이것은 나를 위해 일했다. 여기에이 플러그인을 찾을 수


  7. 7.다음 코드는 나를 위해 일한

    다음 코드는 나를 위해 일한

    //Parameter to be passed
    var data = 'reportid=R3823&isSQL=1&filter=[]';
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "Reporting.jsp"); //url.It can pdf file path
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.responseType = "blob";
    xhr.onload = function () {
        if (this.status === 200) {
            var blob = new Blob([xhr.response]);
            const url = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = 'myFile.pdf';
            a.click();
            setTimeout(function () {
                // For Firefox it is necessary to delay revoking the ObjectURL
                window.URL.revokeObjectURL(data)
                    , 100
            })
        }
    };
    xhr.send(data);
    

  8. 8.PDF와 같은 스트림 데이터를 얻을 포스트 요청에 빈 PDF의 문제를 해결하기 위해, 우리는 요청에 'arraybuffer'또는 '덩어리'로 응답 유형을 추가 할 필요가

    PDF와 같은 스트림 데이터를 얻을 포스트 요청에 빈 PDF의 문제를 해결하기 위해, 우리는 요청에 'arraybuffer'또는 '덩어리'로 응답 유형을 추가 할 필요가

    $.ajax({
      url: '<URL>',
      type: "POST",
      dataType: 'arraybuffer',
      success: function(data) {
        let blob = new Blob([data], {type: 'arraybuffer'});
        let link = document.createElement('a');
        let objectURL = window.URL.createObjectURL(blob);
        link.href = objectURL;
        link.target = '_self';
        link.download = "fileName.pdf";
        (document.body || document.documentElement).appendChild(link);
        link.click();
        setTimeout(()=>{
            window.URL.revokeObjectURL(objectURL);
            link.remove();
        }, 100);
      }
    });
    

  9. 9.Mayur Padshala에 의해 주어진 답에 관한 것은이 아약스를 통해 PDF 파일을 다운로드 할 수있는 올바른 논리지만 다른 사람들이 코멘트에보고으로이 솔루션은 참으로 빈의 PDF를 다운로드합니다.

    Mayur Padshala에 의해 주어진 답에 관한 것은이 아약스를 통해 PDF 파일을 다운로드 할 수있는 올바른 논리지만 다른 사람들이 코멘트에보고으로이 솔루션은 참으로 빈의 PDF를 다운로드합니다.

    그 이유는이 질문의 허용 대답에 설명되어 있습니다 : jQuery를은 아직 일부 HTML5 XHR v2의 기능을 구현이 개선 요청이 설명을 참조하지 않는 한, AJAX 요청을 사용하여 이진 데이터를로드 할 몇 가지 문제가 있습니다.

    다음과 같이해야하는 XMLHTTPRequest 코드를 사용하여 이렇게 :

    var req = new XMLHttpRequest();
    req.open("POST", "URL", true);
    req.responseType = "blob";
    req.onload = function (event) {
        var blob = req.response;
        var link=document.createElement('a');
        link.href=window.URL.createObjectURL(blob);
        link.download="name_for_the_file_to_save_with_extention";
        link.click();
    }
    

  10. 10.위 아약스 코드에서 다음 숨겨진 iframe을 만들기 :

    위 아약스 코드에서 다음 숨겨진 iframe을 만들기 :

    URL :. document.getElementById를 ( 'myiframeid') SRC = your_server_side_url,

    상기 window.open (대응)를 제거;


  11. 11.이 조각은, 같은 문제에 직면 응답 파일은 프로그램 된 클릭 이벤트를 사용하여 다운로드합니다 것입니다 각 JS 사용자를위한 것입니다. 이 경우, 상기 헤더가 포함 서버 이름 및 내용 / 타입에 의해 보내졌다.

    이 조각은, 같은 문제에 직면 응답 파일은 프로그램 된 클릭 이벤트를 사용하여 다운로드합니다 것입니다 각 JS 사용자를위한 것입니다. 이 경우, 상기 헤더가 포함 서버 이름 및 내용 / 타입에 의해 보내졌다.

    $http({
        method: 'POST', 
        url: 'DownloadAttachment_URL',
        data: { 'fileRef': 'filename.pdf' }, //I'm sending filename as a param
        headers: { 'Authorization': $localStorage.jwt === undefined ? jwt : $localStorage.jwt },
        responseType: 'arraybuffer',
    }).success(function (data, status, headers, config) {
        headers = headers();
        var filename = headers['x-filename'];
        var contentType = headers['content-type'];
        var linkElement = document.createElement('a');
        try {
            var blob = new Blob([data], { type: contentType });
            var url = window.URL.createObjectURL(blob);
    
            linkElement.setAttribute('href', url);
            linkElement.setAttribute("download", filename);
    
            var clickEvent = new MouseEvent("click", {
                "view": window,
                "bubbles": true,
                "cancelable": false
            });
            linkElement.dispatchEvent(clickEvent);
        } catch (ex) {
            console.log(ex);
        }
    }).error(function (data, status, headers, config) {
    }).finally(function () {
    
    });
    

  12. 12.이 당신에게 몇 시간을 저장하고 당신이 두통을 아끼지 바랍니다. 그것은이 알아낼 걸 렸어요하지만 주소 표시 줄이 완벽하게 일을 통해 그것을 요청하는 동안 일반 $의 아약스 () 요청을하는 것은, 내 PDF 파일을 파괴. 해결 방법이 있었다 :

    이 당신에게 몇 시간을 저장하고 당신이 두통을 아끼지 바랍니다. 그것은이 알아낼 걸 렸어요하지만 주소 표시 줄이 완벽하게 일을 통해 그것을 요청하는 동안 일반 $의 아약스 () 요청을하는 것은, 내 PDF 파일을 파괴. 해결 방법이 있었다 :

    download.js 포함 : http://danml.com/download.html

    그리고 대신에 $ 아약스 () 요청의 XMLHttpRequest를 사용합니다.

        var ajax = new XMLHttpRequest(); 
    
        ajax.open("GET", '/Admin/GetPdf' + id, true); 
        ajax.onreadystatechange = function(data) { 
            if (this.readyState == 4)
            {
                if (this.status == 200)
                {
                    download(this.response, "report.pdf", "application/pdf");
    
                }
                else if (this.responseText != "")
                {
                    alert(this.responseText);
                }
            }
            else if (this.readyState == 2)
            {
                if (this.status == 200)
                {
                    this.responseType = "blob";
                }
                else
                {
                    this.responseType = "text";
                }
            }
        };
    
        ajax.send(null);
    

  13. 13.당신은 아약스와 함께 할해야합니까? 그것은 iframe에로드 할 수있는 가능성을하지 않을 수 있을까?

    당신은 아약스와 함께 할해야합니까? 그것은 iframe에로드 할 수있는 가능성을하지 않을 수 있을까?


  14. 14.var에 XHR; VAR beforeSend = 함수 () { $ ( '# pleasewaitDL') 모달 ( '쇼.'); } () {(기능 $ $ ( '#의 print_brochure_link'). ((기능을 클릭) { beforeSend (); XHR = 새로운 XMLHttpRequest 객체 (); xhr.open ( "GET", $ ( '# preparedPrintModalForm') ATTR ( '액션'), 진정한.); xhr.responseType = "얼룩"; xhr.onload = 함수 (E) { 경우 (this.status === 200) { var 파일은 window.URL.createObjectURL (this.response를) =; VAR A = document.createElement ( "A"); a.href = 파일; a.download = this.response.name || "속성 브로셔"; CONSOLE.LOG (파일); document.body.appendChild (a); a.click (); window.onfocus = 함수 () { document.body.removeChild (a) } $ ( '# pleasewaitDL') 모달 ( '숨기기.'); }; }; 위해 xhr.send ($ ( '# preparedPrintModalForm') 직렬화 ().); }); $ ( '# pleasewaitDLCancel'). ((기능을 클릭) { xhr.abort (); }); });

    var에 XHR; VAR beforeSend = 함수 () { $ ( '# pleasewaitDL') 모달 ( '쇼.'); } () {(기능 $ $ ( '#의 print_brochure_link'). ((기능을 클릭) { beforeSend (); XHR = 새로운 XMLHttpRequest 객체 (); xhr.open ( "GET", $ ( '# preparedPrintModalForm') ATTR ( '액션'), 진정한.); xhr.responseType = "얼룩"; xhr.onload = 함수 (E) { 경우 (this.status === 200) { var 파일은 window.URL.createObjectURL (this.response를) =; VAR A = document.createElement ( "A"); a.href = 파일; a.download = this.response.name || "속성 브로셔"; CONSOLE.LOG (파일); document.body.appendChild (a); a.click (); window.onfocus = 함수 () { document.body.removeChild (a) } $ ( '# pleasewaitDL') 모달 ( '숨기기.'); }; }; 위해 xhr.send ($ ( '# preparedPrintModalForm') 직렬화 ().); }); $ ( '# pleasewaitDLCancel'). ((기능을 클릭) { xhr.abort (); }); });


  15. 15.이 파일 스트림 (그래서 물리적으로 저장되지 PDF)와 함께 작업해야하는 경우 우리가 당신이 페이지를 다시로드하지 않고 PDF를 다운로드하려는처럼, 다음 함수는 우리를 위해 작동합니다 :

    이 파일 스트림 (그래서 물리적으로 저장되지 PDF)와 함께 작업해야하는 경우 우리가 당신이 페이지를 다시로드하지 않고 PDF를 다운로드하려는처럼, 다음 함수는 우리를 위해 작동합니다 :

    HTML

    <div id="download-helper-hidden-container" style="display:none">
         <form id="download-helper-form" target="pdf-download-output" method="post">
                <input type="hidden" name="downloadHelperTransferData" id="downloadHelperTransferData" />
         </form>
         <iframe id="pdf-helper-output" name="pdf-download-output"></iframe>
    </div>
    

    자바 스크립트

    var form = document.getElementById('download-helper-form');
    $("#downloadHelperTransferData").val(transferData);
    form.action = "ServerSideFunctionWhichWritesPdfBytesToResponse";
    form.submit();
    

    때문에 목표 = "PDF 다운로드 출력"에 응답 iframe이 기입되고, 그러므로 어떤 페이지 새로 고침이 실행되지 않지만 PDF 응답 스트림이 다운로드 등 브라우저에서 출력된다.

  16. from https://stackoverflow.com/questions/1999607/download-and-open-pdf-file-using-ajax by cc-by-sa and MIT license