Ajax를 사용하여 PDF 파일 다운로드 및 열기
PDF 형식입니다.contentType
이치노
public class MyAction extends ActionSupport
{
public String execute() {
...
...
File report = signedPdfExporter.generateReport(xyzData, props);
inputStream = new FileInputStream(report);
contentDisposition = "attachment=\"" + report.getName() + "\"";
contentType = "application/pdf";
return SUCCESS;
}
}
는 이것을 는는라고 .action
을 브라우저에이 스트림을 브라우저에 전달하는 방법을 모르겠습니다.몇 가지 시도해 봤지만 소용이 없었어요.
$.ajax({
type: "POST",
url: url,
data: wireIdList,
cache: false,
success: function(response)
{
alert('got response');
window.open(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('Error occurred while opening fax template'
+ getAjaxErrorString(textStatus, errorThrown));
}
});
위의 오류는 다음과 같습니다.
브라우저에서 이 서버가 인식할 수 없는 요청을 보냈습니다.
내가 이걸 작동시킨 방법은 이렇다.
$.ajax({
url: '<URL_TO_FILE>',
success: function(data) {
var blob=new Blob([data]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="<FILENAME_TO_SAVE_WITH_EXTENSION>";
link.click();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
다운로드를 사용하여 답변을 업데이트했습니다.js
$.ajax({
url: '<URL_TO_FILE>',
success: download.bind(true, "<FILENAME_TO_SAVE_WITH_EXTENSION>", "<FILE_MIME_TYPE>")
});
그냥...<a>
합니다.content-disposition
로로 합니다.attachment
서버측 코드로 설정합니다.이렇게 하면 부모 페이지가 열린 채로 남습니다(그렇지 않으면 불필요하게 Ajax를 선택한 이유는 무엇입니까?).문자 데이터가 .PDF 형식입니다.바이너리 데이터입니다. 건 할 수 없어요$(element).load()
이 경우 완전히 새로운 요청을 사용해야 합니다.그러기 위해서<a href="pdfservlet/filename.pdf">pdf</a>
딱 맞네요.
서버측 코드에 대한 자세한 정보를 얻으려면 사용하는 언어에 대해 자세히 설명하고 코드 시행의 발췌를 게시해야 합니다.
나는 정말로 과거의 어떤 대답도 원본 포스터의 문제점을 발견했다고 생각하지 않는다.모두 포스터가 데이터를 POST하고 이에 대한 응답을 다운로드 받는 동안 GET 요청을 가정합니다.
더 나은 답을 찾는 과정에서 Ajax와 유사한 파일 다운로드를 요청하는 이 jQuery 플러그인을 발견했습니다.
"심장"에 입력 필드로 지정된 데이터를 포함하는 "임시" HTML 양식을 만듭니다.이 양식은 문서에 추가되고 원하는 URL에 게시됩니다. 그 직후에 양식은 다시 삭제됩니다.
jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo('body').submit().remove()
업데이트 Mayur의 답변은 제가 참조한 jQuery 플러그인에 비해 상당히 유망하고 매우 단순해 보입니다.
이것이 내가 이 문제를 해결하는 방법이다.
이 게시물에 대한 Jonathan Amend의 답변이 저에게 많은 도움이 되었습니다.
하다
자세한 내용은 위의 소스 코드를 사용하여 JQuery Ajax 요청(GET, POST, PUT 등)을 사용하여 파일을 다운로드할 수 있습니다.또한 매개 변수를 JSON으로 업로드하고 컨텐츠 유형을 application/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>
2개의 입력 텍스트, 1개의 선택과 버튼 요소가 있는 심플한 폼.
javascript 페이지 소스:
<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 라이브러리에 추가하기 위해 이 클래스를 만들었습니다.재사용이 가능합니다.도움이 됐으면 좋겠다.
가 검색 이기 때문에 가 있었던 과 같은 코드입니다.File(memoryStream.GetBuffer(), "application/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();
}
});
이 플러그인을 사용하면 양식을 만들고 제출한 다음 페이지에서 제거할 수 있습니다.
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
);
이건 나한테 효과가 있었어.이 플러그인을 찾았습니다.
Mayur Padshala가 제시한 답변에 대해 이것은 ajax를 통해 pdf 파일을 다운로드하는 올바른 논리이지만, 다른 사람들이 코멘트로 보고하는 것처럼 이 솔루션은 실제로 빈 pdf를 다운로드하는 것입니다.
그 이유는 이 질문의 수락된 답변에서 설명되어 있습니다.jQuery는 아직 HTML5 XHR v2 기능을 구현하지 않았기 때문에 AJAX 요청을 사용하여 바이너리 데이터를 로드하는 데 몇 가지 문제가 있습니다.이 확장 요청과 이 설명을 참조하십시오.
이렇게 쓰면서HTMLHTTPRequest
을 사용하다
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();
}
다음 코드가 작동했습니다.
//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);
PDF와 같은 스트림 데이터를 얻기 위해 요청 시 빈 PDF 문제를 수정하려면 요청 시 'arraybuffer' 또는 'blob'으로 응답 유형을 추가해야 합니다.
$.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);
}
});
이것으로 몇 시간이 절약되고 두통이 없기를 바랍니다.이것을 알아내는 데 시간이 걸렸지만, 일반적인 $.ajax() 요청을 하면 PDF 파일이 망가져 버렸고, 주소 표시줄을 통해 요청하면 완벽하게 작동했습니다.솔루션은 다음과 같습니다.
include download.http://http://danml.com/download.html
그런 다음 $.ajax() 요청 대신 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);
숨겨진 iframe을 만든 다음 위의 Ajax 코드에 입력합니다.
url: document.getElementById('myiframeid').src = your_server_side_url
,
뺄게요.window.open(response);
이 스니펫은 동일한 문제에 직면하게 될 각도 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 () {
});
var xhr;
var beforeSend = function(){
$('#pleasewaitDL').modal('show');
}
$(function () {
$('#print_brochure_link').click(function(){
beforeSend();
xhr = new XMLHttpRequest();
xhr.open("GET",$('#preparedPrintModalForm').attr('action'), true);
xhr.responseType = "blob";
xhr.onload = function (e) {
if (this.status === 200) {
var file = window.URL.createObjectURL(this.response);
var a = document.createElement("a");
a.href = file;
a.download = this.response.name || "Property Brochure";
console.log(file);
document.body.appendChild(a);
a.click();
window.onfocus = function () {
document.body.removeChild(a)
}
$('#pleasewaitDL').modal('hide');
};
};
xhr.send($('#preparedPrintModalForm').serialize());
});
$('#pleasewaitDLCancel').click(function() {
xhr.abort();
});
});
이 문제를 해결할 수 있는 솔루션을 찾았습니다(jquery ajax 사용 시 공백 PDF).여기서 마법의 솔루션을 찾았습니다.https://www.py4u.net/discuss/904599 (정답 2) 。이 솔루션에는 ajax 콜에 xhrFields를 추가합니다.
xhrFields: {
responseType: 'blob'
}
작업 예:
$.ajax({
url: "myUrl",
type: 'GET',
headers: {"token": mySecurityToken},
xhrFields: {
responseType: 'blob'
},
data: {id: myId}
}).done(function( data, statusText, xhr ) {
var filename = "";
var disposition = xhr.getResponseHeader("Content-Disposition");
if (disposition && (disposition.indexOf("attachment") !== -1) || disposition.indexOf("filename") !== -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([data], {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
}
})
저는 이것이 여러분 중 많은 사람들에게 이 불쾌한 문제를 해결해 주길 바랍니다.
당사처럼 파일 스트림(물리적으로 저장된 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();
target="pdf-response-output"으로 인해 응답은 iframe에 기록되므로 페이지 새로고침은 실행되지 않지만 pdf-response-stream은 다운로드로 브라우저에 출력됩니다.
모든 파일 유형에 대해 100% OK
// download the file
var link = document.createElement('a'),
filename = fname;
link.href = URL.createObjectURL(data);
link.download = filename;
link.click();
꼭 아약스랑 해야 돼?iframe에 넣을 수 있지 않을까요?
가장 좋은 방법은 제공된 링크를 사용하여 앵커 또는 폼을 수행하는 것이지만, 검증을 수행해야 하거나 jquery를 사용하여 다른 경우 jquery를 사용하여 폼을 추가하고 제출하는 것입니다(요청 처리는 서버 측에서 첨부 파일로 설정하는 것을 잊지 마십시오.
<form id="pdf-form" action="/link_to/download_your.pdf" accept-charset="UTF-8" method="get">
<input type="hidden" name="data" id="data" value="your data"></form>
그리고.
<a href="javascript:void(0);" id="pdf">Download my Pdf</a>
그 후, 의기양양하게
$('#pdf').click(function () {
// your data if it json do it like this JSON.stringify(your_data_as_json)
$('#data').val(data);
$('#pdf-form').submit();
})
언급URL : https://stackoverflow.com/questions/1999607/download-and-open-pdf-file-using-ajax
'programing' 카테고리의 다른 글
DateTime을 문자열 PHP로 변환 (0) | 2023.01.01 |
---|---|
디렉토리에서 모든 PHP 파일을 포함()하려면 어떻게 해야 합니까? (0) | 2023.01.01 |
스프링 부트 - 클래스 경로 리소스에 정의된 'dataSource' 이름의 콩을 만드는 동안 오류가 발생했습니다. (0) | 2023.01.01 |
자바어로 뮤텍스와 세마포어가 뭐죠?주된 차이점은 무엇입니까? (0) | 2023.01.01 |
JavaScript에서 스택과 큐를 구현하려면 어떻게 해야 합니까? (0) | 2023.01.01 |