[JQUERY] jQuery.Ajax하여 파일을 다운로드
JQUERYjQuery.Ajax하여 파일을 다운로드
해결법
-
1.2019 최신 브라우저 업데이트
2019 최신 브라우저 업데이트
이것은 내가 지금 몇 가지주의로 추천하려는 접근 방법이다 :
가져 오기 ( 'https://jsonplaceholder.typicode.com/todos/1') 그 때는 (RESP => resp.blob ()) 그 때는 BLOB (=> { CONST URL = window.URL.createObjectURL (BLOB); CONST A = document.createElement ( "A"); a.style.display = '없음'; a.href = URL; // 파일 이름 당신이 원하는 a.download = 'TODO-1.json'; document.body.appendChild (a); a.click (); window.URL.revokeObjectURL (URL); 경고 ( '파일이 다운로드했다!'); // 또는 당신은 더 나은 UX와 뭔가를 알고 ... }) ( '오!'(() => 경고)) .catch;
2012 원본 jQuery를 / iframe이 / 쿠키 기반의 접근 방식
푸른 색은 Ajax를 통해 때문에 자바 스크립트 수 없습니다 직접 사용자의 컴퓨터에 파일을 저장 (보안 문제 만점)을 할 수 없어, 바로 이것에 대해 완전히이다. 불행하게도 당신은 파일 다운로드가 발생했을 때 사용자 경험이 무엇인지를 통해 작은 제어 할 수 있습니다 파일 다운로드 수단에서 메인 윈도우의 URL을 가리키는.
나는 더 나은 사용자 경험을 제공 할 onsuccess는와 OnFailure 콜백와 전체 파일 다운로드 경험 "와 같은 아약스"는 허용 jQuery를 파일 다운로드를 만들었습니다. 플러그인 해결하고 어떤 방법을 사용하는 일반적인 문제와 액션에 jQuery를 파일 다운로드의 데모에 내 블로그 게시물을 살펴보십시오. 여기 소스입니다
여기 약속과 플러그인 소스를 사용하여 데모 간단한 사용 사례입니다. 데모 페이지뿐만 아니라 많은 다른, '더 나은 UX'의 예를 포함한다.
$.fileDownload('some/file.pdf') .done(function () { alert('File download a success!'); }) .fail(function () { alert('File download failed!'); });
브라우저를 내용에 따라 당신은 당신이 https://github.com/eligrey/FileSaver.js/ IFRAME을 방법의 jQuery 파일 다운로드 사용보다 더 명시 적으로 제어 할 수있는를 사용할 수 있습니다 지원해야합니다.
-
2.나는 그것을 게시합니다, 그래서 아무도 ... 페카의 솔루션 @이를 기록했다. 그것은 다른 사람을 도울 수 있습니다.
나는 그것을 게시합니다, 그래서 아무도 ... 페카의 솔루션 @이를 기록했다. 그것은 다른 사람을 도울 수 있습니다.
당신은 Ajax를 통해이 작업을 수행 할 필요가 없습니다. 그냥 사용
window.location="download.action?para1=value1...."
-
3.당신은 HTML5 때와 수
당신은 HTML5 때와 수
NB : 당신은 JSON이 바이너리 데이터를 인코딩 할 수 없기 때문에 파일 데이터는 base64로 인코딩되어야합니다 반환
내 AJAX 응답에서 나는 데이터 구조를 가지고 그 다음과 같다 :
{ result: 'OK', download: { mimetype: string(mimetype in the form 'major/minor'), filename: string(the name of the file to download), data: base64(the binary data as base64 to download) } }
내가 AJAX를 통해 파일을 저장하려면 다음을 수행 할 수 있음을 의미
var a = document.createElement('a'); if (window.URL && window.Blob && ('download' in a) && window.atob) { // Do it the HTML5 compliant way var blob = base64ToBlob(result.download.data, result.download.mimetype); var url = window.URL.createObjectURL(blob); a.href = url; a.download = result.download.filename; a.click(); window.URL.revokeObjectURL(url); }
함수 base64ToBlob 여기에서 찍은이 기능을 준수하여 사용해야합니다
function base64ToBlob(base64, mimetype, slicesize) { if (!window.atob || !window.Uint8Array) { // The current browser doesn't have the atob function. Cannot continue return null; } mimetype = mimetype || ''; slicesize = slicesize || 512; var bytechars = atob(base64); var bytearrays = []; for (var offset = 0; offset < bytechars.length; offset += slicesize) { var slice = bytechars.slice(offset, offset + slicesize); var bytenums = new Array(slice.length); for (var i = 0; i < slice.length; i++) { bytenums[i] = slice.charCodeAt(i); } var bytearray = new Uint8Array(bytenums); bytearrays[bytearrays.length] = bytearray; } return new Blob(bytearrays, {type: mimetype}); };
서버가 저장 될 덤핑 FILEDATA 인 경우에 좋다. 그러나, 나는 꽤 하나는 HTML4 대체를 구현하는 것이 방법 일 적이 없다
-
4.브라우저 다운로드에게 파일을 만들 수있는 간단한 방법은 그런 요청을하는 것입니다 :
브라우저 다운로드에게 파일을 만들 수있는 간단한 방법은 그런 요청을하는 것입니다 :
function downloadFile(urlToSend) { var req = new XMLHttpRequest(); req.open("GET", urlToSend, true); req.responseType = "blob"; req.onload = function (event) { var blob = req.response; var fileName = req.getResponseHeader("fileName") //if you have the fileName header available var link=document.createElement('a'); link.href=window.URL.createObjectURL(blob); link.download=fileName; link.click(); }; req.send(); }
이 브라우저 다운로드가 나타납니다.
-
5.1. 프레임 워크 불가지론 : 서블릿은 첨부 파일을 다운로드
1. 프레임 워크 불가지론 : 서블릿은 첨부 파일을 다운로드
<!-- with JS --> <a href="javascript:window.location='downloadServlet?param1=value1'"> download </a> <!-- without JS --> <a href="downloadServlet?param1=value1" >download</a>
2. Struts2 프레임 워크 : 액션은 첨부 파일을 다운로드
<!-- with JS --> <a href="javascript:window.location='downloadAction.action?param1=value1'"> download </a> <!-- without JS --> <a href="downloadAction.action?param1=value1" >download</a>
<: 홈페이지의> 태그로 생성 된 URL에 OGNL을 가리키는 태그 : 그것은 를 사용하는 것이 좋을 것이다 :
<!-- without JS, with Struts tags: THE RIGHT WAY --> <s:url action="downloadAction.action" var="url"> <s:param name="param1">value1</s:param> </s:ulr> <s:a href="%{url}" >download</s:a>
위의 경우에, 당신은 파일 필요 (첨부 파일)을 다운로드하고 브라우저 (인라인)에 의해 열리지 할 것을 지정하여 응답 내용 - 처리 헤더를 작성해야합니다. 당신은 너무 컨텐츠 유형을 지정해야합니다, 당신은 (도움말을 실제 진행 막대 그리기 브라우저를) 파일 이름과 길이를 추가 할 수 있습니다.
예를 들어, 우편 번호를 다운로드 할 때 :
response.setContentType("application/zip"); response.addHeader("Content-Disposition", "attachment; filename=\"name of my file.zip\""); response.setHeader("Content-Length", myFile.length()); // or myByte[].length...
Struts2로 (당신은 예를 들어, 서블릿, 직접 스트리밍에 대한 해킹과 액션을 사용하지 않는 경우), 당신은 응답에 직접 쓰기 아무것도 필요하지 않습니다; 간단하게 작동합니다 스트림 결과 유형을 사용하고 struts.xml에서 그것을 구성 : 예를
<result name="success" type="stream"> <param name="contentType">application/zip</param> <param name="contentDisposition">attachment;filename="${fileName}"</param> <param name="contentLength">${fileLength}</param> </result>
3. 프레임 워크 불가지론 (/ Struts2 프레임 워크) : 브라우저 내부 서블릿 (/ 액션) 파일을 여는
대신 그것을 다운로드하는 브라우저 내부의 파일을 열려면, 내용 - 처리 인라인으로 설정해야하지만 대상은 현재 창 위치가 될 수 없습니다; 당신이 자바 스크립트에 의해 생성 된 새 창을 대상으로해야
<!-- From a parent page into an IFrame without javascript --> <a href="downloadServlet?param1=value1" target="iFrameName"> download </a> <!-- In a new window without javascript --> <a href="downloadServlet?param1=value1" target="_blank"> download </a> <!-- In a new window with javascript --> <a href="javascript:window.open('downloadServlet?param1=value1');" > download </a>
-
6.내가 해결 솔루션 (@JohnCulviner 플러그인에서 영감)와 같은 작은 기능을 만들었습니다 :
내가 해결 솔루션 (@JohnCulviner 플러그인에서 영감)와 같은 작은 기능을 만들었습니다 :
// creates iframe and form in it with hidden field, // then submit form with provided data // url - form url // data - data to form field // input_name - form hidden input name function ajax_download(url, data, input_name) { var $iframe, iframe_doc, iframe_html; if (($iframe = $('#download_iframe')).length === 0) { $iframe = $("<iframe id='download_iframe'" + " style='display: none' src='about:blank'></iframe>" ).appendTo("body"); } iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument; if (iframe_doc.document) { iframe_doc = iframe_doc.document; } iframe_html = "<html><head></head><body><form method='POST' action='" + url +"'>" + "<input type=hidden name='" + input_name + "' value='" + JSON.stringify(data) +"'/></form>" + "</body></html>"; iframe_doc.open(); iframe_doc.write(iframe_html); $(iframe_doc).find('form').submit(); }
클릭 이벤트와 데모 :
$('#someid').on('click', function() { ajax_download('/download.action', {'para1': 1, 'para2': 2}, 'dataname'); });
-
7.저도 같은 문제에 직면하고 성공적으로 해결했다. 내 사용 사례는 이것이다.
저도 같은 문제에 직면하고 성공적으로 해결했다. 내 사용 사례는 이것이다.
"포스트 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을 수정합니다. 당신은 당신의 파일 유형에 따라 설정해야합니다. 당신은 파일의 종류를 다운로드하려면이 기술을 사용할 수 있습니다.
-
8.좋아, ndpu의 코드를 heres ajax_download의 개선 (내가 생각하는) 버전을 기반으로 -
좋아, ndpu의 코드를 heres ajax_download의 개선 (내가 생각하는) 버전을 기반으로 -
function ajax_download(url, data) { var $iframe, iframe_doc, iframe_html; if (($iframe = $('#download_iframe')).length === 0) { $iframe = $("<iframe id='download_iframe'" + " style='display: none' src='about:blank'></iframe>" ).appendTo("body"); } iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument; if (iframe_doc.document) { iframe_doc = iframe_doc.document; } iframe_html = "<html><head></head><body><form method='POST' action='" + url +"'>" Object.keys(data).forEach(function(key){ iframe_html += "<input type='hidden' name='"+key+"' value='"+data[key]+"'>"; }); iframe_html +="</form></body></html>"; iframe_doc.open(); iframe_doc.write(iframe_html); $(iframe_doc).find('form').submit(); }
이 같은이 사용 -
$('#someid').on('click', function() { ajax_download('/download.action', {'para1': 1, 'para2': 2}); });
입력에서보다 앞의 예와 같이 당 JSON 문자열로 인코딩 오는 것처럼 PARAMS는 적절한 포스트 PARAMS로 전송된다.
주의해야 할 점은 : 그 형태에 변수 주입의 가능성에 대해주의하십시오. 이 변수를 인코딩 할 수있는 안전한 방법이있을 수 있습니다. 또한 그들을 탈출 명상.
-
9.여기에 내가 무슨 짓을했는지, 순수 자바 스크립트와 HTML입니다. 그것을 테스트하지 않았하지만이 모든 브라우저에서 작동합니다.
여기에 내가 무슨 짓을했는지, 순수 자바 스크립트와 HTML입니다. 그것을 테스트하지 않았하지만이 모든 브라우저에서 작동합니다.
var iframe = document.createElement('iframe'); iframe.id = "IFRAMEID"; iframe.style.display = 'none'; document.body.appendChild(iframe); iframe.src = 'SERVERURL'+'?' + $.param($scope.filtro); iframe.addEventListener("load", function () { console.log("FILE LOAD DONE.. Download should start now"); });
@RequestMapping(value = "/rootto/my/xlsx", method = RequestMethod.GET) public void downloadExcelFile(@RequestParam(value = "param1", required = false) String param1, HttpServletRequest request, HttpServletResponse response) throws ParseException { Workbook wb = service.getWorkbook(param1); if (wb != null) { try { String fileName = "myfile_" + sdf.format(new Date()); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + ".xlsx\""); wb.write(response.getOutputStream()); response.getOutputStream().close(); } catch (IOException e) { e.printStackTrace(); } } }
-
10.AJAX하여받은 후 파일을 다운로드하는 방법
AJAX하여받은 후 파일을 다운로드하는 방법
파일이 오랜 시간 동안 생성 될 때 그것은 편리하고 당신은 프리 로더를 보여줄 필요
예는 웹 양식을 제출하는 경우 :
<script> $(function () { $('form').submit(function () { $('#loader').show(); $.ajax({ url: $(this).attr('action'), data: $(this).serialize(), dataType: 'binary', xhrFields: { 'responseType': 'blob' }, success: function(data, status, xhr) { $('#loader').hide(); // if(data.type.indexOf('text/html') != -1){//If instead of a file you get an error page // var reader = new FileReader(); // reader.readAsText(data); // reader.onload = function() {alert(reader.result);}; // return; // } var link = document.createElement('a'), filename = 'file.xlsx'; // if(xhr.getResponseHeader('Content-Disposition')){//filename // filename = xhr.getResponseHeader('Content-Disposition'); // filename=filename.match(/filename="(.*?)"/)[1]; // filename=decodeURIComponent(escape(filename)); // } link.href = URL.createObjectURL(data); link.download = filename; link.click(); } }); return false; }); }); </script>
기능 선택 사항의 예를 단순화하기 위해 주석.
필요가 서버에 임시 파일을 만들 수 없습니다.
jQuery를 v2.2.4 확인합니다. 이전 버전에 오류가있을 것입니다 :
Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').
-
11.
function downloadURI(uri, name) { var link = document.createElement("a"); link.download = name; link.href = uri; link.click(); }
-
12.레일, 나는 이런 식으로 할 :
레일, 나는 이런 식으로 할 :
function download_file(file_id) { let url = '/files/' + file_id + '/download_file'; $.ajax({ type: 'GET', url: url, processData: false, success: function (data) { window.location = url; }, error: function (xhr) { console.log(' Error: >>>> ' + JSON.stringify(xhr)); } }); }
트릭은에서는 window.location 부분입니다. 컨트롤러의 방법 외모 좋아 :
# GET /files/{:id}/download_file/ def download_file send_file(@file.file, :disposition => 'attachment', :url_based_filename => false) end
-
13.사용 window.open https://developer.mozilla.org/en-US/docs/Web/API/Window/open
사용 window.open https://developer.mozilla.org/en-US/docs/Web/API/Window/open
예를 들어, 당신은 클릭 핸들러에 코드 줄을 넣을 수 있습니다 :
window.open('/file.txt', '_blank');
그것은 (때문에 '_blank'창 이름의) 새 탭을 열 것이며, 그 탭은 URL을 엽니 다.
서버 측 코드는 이런 식으로 뭔가를해야한다 :
res.set('Content-Disposition', 'attachment; filename=file.txt');
그리고 그 방법은, 브라우저는 단지 그들에게 파일을 보여주는 대신, 파일을 디스크에 저장하라는 메시지를 표시합니다. 또한 자동으로 방금 연하는 탭을 닫습니다.
-
14.나는 CSV 파일을 다운로드 한 후 다운로드가 완료되면 뭔가. 그래서 적절한 콜백 함수를 구현해야합니다.
나는 CSV 파일을 다운로드 한 후 다운로드가 완료되면 뭔가. 그래서 적절한 콜백 함수를 구현해야합니다.
나는 다운로드를 마친 후 프로그램을 운영 할 수 없기 때문에 =에서는 window.location을 사용하면 "..."좋은 생각이 아니다. 이런 식으로 뭔가, 변경 헤더 그래서 그것은 좋은 생각이 아니다.
패치는 IE 11과 window.URL.createObjectURL는 IE 11.You이를 참조 할 수 있습니다 지원할 수 지원할 수 있지만 좋은 대안이다.
이 내 코드, 그것은 흐르 알람의 코드와 유사하다. 하지만 당신은 window.URL.createObjectURL 아마 메모리 누수를 만드는 것이주의를 기울여야한다. 이 작업을 참조 할 수 있습니다. 응답이 도착하면, 데이터는 브라우저의 메모리에 저장됩니다. 당신이 링크를 클릭하기 전에 그래서, 파일이 다운로드되었습니다. 그것은 당신이 다운로드 후 아무것도 할 수 있다는 것을 의미한다.
$.ajax({ url: 'your download url', type: 'GET', }).done(function (data, textStatus, request) { // csv => Blob var blob = new Blob([data]); // the file name from server. var fileName = request.getResponseHeader('fileName'); if (window.navigator && window.navigator.msSaveOrOpenBlob) { // for IE window.navigator.msSaveOrOpenBlob(blob, fileName); } else { // for others var url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; a.download = fileName; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); //Do something after download ... } }).then(after_download) }
-
15.파일을 다운로드를 위해 위의 대답에 좀 더 일을 추가
파일을 다운로드를 위해 위의 대답에 좀 더 일을 추가
다음 바이트 배열을 생성하는 일부 자바 스프링 코드는
@RequestMapping(value = "/downloadReport", method = { RequestMethod.POST }) public ResponseEntity<byte[]> downloadReport( @RequestBody final SomeObejct obj, HttpServletResponse response) throws Exception { OutputStream out = new ByteArrayOutputStream(); // write something to output stream HttpHeaders respHeaders = new HttpHeaders(); respHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); respHeaders.add("X-File-Name", name); ByteArrayOutputStream bos = (ByteArrayOutputStream) out; return new ResponseEntity<byte[]>(bos.toByteArray(), respHeaders, HttpStatus.CREATED); }
이제 FileSaver.js를 사용하여 자바 스크립트 코드, 코드 아래에있는 파일을 다운로드 할 수 있습니다
var json=angular.toJson("somejsobject"); var url=apiEndPoint+'some url'; var xhr = new XMLHttpRequest(); //headers('X-File-Name') xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 201) { var res = this.response; var fileName=this.getResponseHeader('X-File-Name'); var data = new Blob([res]); saveAs(data, fileName); //this from FileSaver.js } } xhr.open('POST', url); xhr.setRequestHeader('Authorization','Bearer ' + token); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.responseType = 'arraybuffer'; xhr.send(json);
위의 의지 다운로드 파일
-
16.좋아, 그래서 여기에 MVC를 사용하는 경우 작업 코드는 당신은 컨트롤러에서 파일을 받고
좋아, 그래서 여기에 MVC를 사용하는 경우 작업 코드는 당신은 컨트롤러에서 파일을 받고
당신이 당신의 바이트 배열 선언 및 채우기, 당신이해야 할 유일한 것은이 있다고 할 수 있습니다하면 파일 기능을 (System.Web.Mvc를 사용)를 사용하는 것입니다
byte[] bytes = .... insert your bytes in the array return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, "nameoffile.exe");
다음, 동일한 컨트롤러에서 추가 2 개 기능 양태에서는
protected override void OnResultExecuting(ResultExecutingContext context) { CheckAndHandleFileResult(context); base.OnResultExecuting(context); } private const string FILE_DOWNLOAD_COOKIE_NAME = "fileDownload"; /// <summary> /// If the current response is a FileResult (an MVC base class for files) then write a /// cookie to inform jquery.fileDownload that a successful file download has occured /// </summary> /// <param name="context"></param> private void CheckAndHandleFileResult(ResultExecutingContext context) { if (context.Result is FileResult) //jquery.fileDownload uses this cookie to determine that a file download has completed successfully Response.SetCookie(new HttpCookie(FILE_DOWNLOAD_COOKIE_NAME, "true") { Path = "/" }); else //ensure that the cookie is removed in case someone did a file download without using jquery.fileDownload if (Request.Cookies[FILE_DOWNLOAD_COOKIE_NAME] != null) Response.Cookies[FILE_DOWNLOAD_COOKIE_NAME].Expires = DateTime.Now.AddYears(-1); }
다음은 "성공"또는 "실패"콜백을 다운로드 컨트롤러를 호출하여 얻을 수있을 것입니다
$.fileDownload(mvcUrl('name of the controller'), { httpMethod: 'POST', successCallback: function (url) { //insert success code }, failCallback: function (html, url) { //insert fail code } });
-
17.나는 그것이 실제로 Ajax를 사용하여 아니지만 당신이 다운로드를 요청하고 다운로드가 실제로 시작할 때 콜백을 얻기 위해 자바 스크립트 호출을 사용할 수 있도록 않는 수정을 발견했다. 링크를 보내기 전에 파일을 작성하는 데 조금 걸리는 서버 측 스크립트를 실행하는 경우 난이 도움이되었다고합니다. 당신이 그들을 경고 할 수 있도록의 처리를 한 다음 마지막으로 처리 통지 그 파일 삭제를 보내 않는 경우 있음. 나는 파일이 요청 될 때 이벤트가 발생하고 실제로 다운로드가 다른 시작할 때 가질 수 있도록로 시작하는 아약스를 통해 파일을로드 원했고 이유입니다.
나는 그것이 실제로 Ajax를 사용하여 아니지만 당신이 다운로드를 요청하고 다운로드가 실제로 시작할 때 콜백을 얻기 위해 자바 스크립트 호출을 사용할 수 있도록 않는 수정을 발견했다. 링크를 보내기 전에 파일을 작성하는 데 조금 걸리는 서버 측 스크립트를 실행하는 경우 난이 도움이되었다고합니다. 당신이 그들을 경고 할 수 있도록의 처리를 한 다음 마지막으로 처리 통지 그 파일 삭제를 보내 않는 경우 있음. 나는 파일이 요청 될 때 이벤트가 발생하고 실제로 다운로드가 다른 시작할 때 가질 수 있도록로 시작하는 아약스를 통해 파일을로드 원했고 이유입니다.
첫 페이지에 JS
function expdone() { document.getElementById('exportdiv').style.display='none'; } function expgo() { document.getElementById('exportdiv').style.display='block'; document.getElementById('exportif').src='test2.php?arguments=data'; }
iframe이
<div id="exportdiv" style="display:none;"> <img src="loader.gif"><br><h1>Generating Report</h1> <iframe id="exportif" src="" style="width: 1px;height: 1px; border:0px;"></iframe> </div>
다음 다른 파일 :
<!DOCTYPE html> <html> <head> <script> function expdone() { window.parent.expdone(); } </script> </head> <body> <iframe id="exportif" src="<?php echo "http://10.192.37.211/npdtracker/exportthismonth.php?arguments=".$_GET["arguments"]; ?>"></iframe> <script>document.getElementById('exportif').onload= expdone;</script> </body></html>
난 그럼 더 PHP가 필요하지 않을 것입니다 JS를 사용하여 데이터 가져 오기를 읽을 수있는 방법이 있다고 생각. 그러나 나는 손 떨어져 그것을 모르는 내가 지원을 사용하고 서버가 나를 위해 이렇게이 작품 PHP로. 이 사람을 도움이 경우에 나는 그것을 공유하고자합니다.
-
18.당신이 jQuery를 파일 다운로드를 사용하려면, IE이 유의하십시오. 당신은 응답을 재설정해야하거나 다운로드하지 않습니다
당신이 jQuery를 파일 다운로드를 사용하려면, IE이 유의하십시오. 당신은 응답을 재설정해야하거나 다운로드하지 않습니다
//The IE will only work if you reset response getServletResponse().reset(); //The jquery.fileDownload needs a cookie be set getServletResponse().setHeader("Set-Cookie", "fileDownload=true; path=/"); //Do the reset of your action create InputStream and return
당신의 행동은) (액세스 getServletResponse에 ServletResponseAware을 구현할 수 있습니다
-
19.당신이 아약스 호출을 통해 그것을 할 수 없다고 확실하다.
당신이 아약스 호출을 통해 그것을 할 수 없다고 확실하다.
그러나, 해결 방법이 있습니다.
단계 :
파일을 다운로드 form.submit ()를 사용하는 경우, 당신이 할 수있는 것은 :
이 파일은 예를 들어 form.submit ()를 한 후 다운로드 할 필요가 있는지 여부를 결정하고자 할 때 경우에 도움이된다 : form.submit ()에서 예외가 대신 서버 측에 발생하는 경우가 있습니다 충돌, 당신은 이러한 경우에, 클라이언트 측이 구현의 힘의 도움을 사용자 정의 메시지를 표시 할 수도 있습니다.
-
20.아약스에서 웹 페이지를 다운로드 할 수있는 다른 해결책이있다. 하지만 먼저 처리 한 후 다운로드해야 페이지를 참조하고있다.
아약스에서 웹 페이지를 다운로드 할 수있는 다른 해결책이있다. 하지만 먼저 처리 한 후 다운로드해야 페이지를 참조하고있다.
먼저 결과 다운로드에서 페이지 처리를 분리해야합니다.
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"); ...
나는 그것이 나를 위해이었다 용액으로, 많은 도움이 될 수 있기를 바랍니다.
-
21.
The HTML Code:- '<button type="button" id="GetFile">Get File!</button>' The jQuery Code:- '$('#GetFile').on('click', function () { $.ajax({ url: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/172905/test.pdf', method: 'GET', xhrFields: { responseType: 'blob' }, success: function (data) { var a = document.createElement('a'); var url = window.URL.createObjectURL(data); a.href = url; a.download = 'myfile.pdf'; document.body.append(a); a.click(); a.remove(); window.URL.revokeObjectURL(url); } }); });'
-
22.즉, (내가 asp.net 코어를 사용하고) 모든 브라우저에서 매우 잘 작동의
즉, (내가 asp.net 코어를 사용하고) 모든 브라우저에서 매우 잘 작동의
onDownload 함수 () { CONST API = 'Url.Action @ ( "시켜라", "MYCONTROLLER")'; VAR 양식 (document.getElementById를 ( 'Form1을')) 새로운 FormData를 =; 페치 (API {본체 : 형태에있어서 "POST"}) 그 때는 (RESP => resp.blob ()) 그 때는 BLOB (=> { CONST URL = window.URL.createObjectURL (BLOB); $ ( '#의 link 다운로드') ATTR ( '다운로드', 'Attachement.zip.'); $ ( '#의 link 다운로드') ATTR ( "HREF", URL).; $ ( '#의 link 다운로드') .fadeIn (3000, 함수() { }); }) .catch (() => 경보 ( '은 에러가 발생한')); } <버튼 유형 = "버튼"onclick을 = "onDownload ()"클래스 = "BTN BTN-차 BTN-SM"> 파일을 처리하기 위해 클릭 버튼>
을 다운로드하려면 클릭 <형태 ASP 제어기 = "MYCONTROLLER"ASP 액션 = "시켜라"ID = "form1에"> FORM>function onDownload() { const api = '@Url.Action("myaction", "mycontroller")'; //form1 is your id form, and to get data content of form var form = new FormData(document.getElementById('form1')); fetch(api, { body: form, method: "POST"}) .then(resp => resp.blob()) .then(blob => { const url = window.URL.createObjectURL(blob); $('#linkdownload').attr('download', 'Attachments.zip'); $('#linkdownload').attr("href", url); $('#linkdownload') .fadeIn(3000, function() { }); }) .catch(() => alert('An error occurred')); }
-
23.서버가 응답 파일 다시 작성하는 경우 (경우 쿠키를 포함 당신은 단순히 값으로 양식을 작성하여 제출) 파일 다운로드가 시작 여부를 결정하는 데 사용할 :
서버가 응답 파일 다시 작성하는 경우 (경우 쿠키를 포함 당신은 단순히 값으로 양식을 작성하여 제출) 파일 다운로드가 시작 여부를 결정하는 데 사용할 :
function ajaxPostDownload(url, data) { var $form; if (($form = $('#download_form')).length === 0) { $form = $("<form id='download_form'" + " style='display: none; width: 1px; height: 1px; position: absolute; top: -10000px' method='POST' action='" + url + "'></form>"); $form.appendTo("body"); } //Clear the form fields $form.html(""); //Create new form fields Object.keys(data).forEach(function (key) { $form.append("<input type='hidden' name='" + key + "' value='" + data[key] + "'>"); }); //Submit the form post $form.submit(); }
용법:
ajaxPostDownload('/fileController/ExportFile', { DownloadToken: 'newDownloadToken', Name: $txtName.val(), Type: $txtType.val() });
컨트롤러 방법 :
[HttpPost] public FileResult ExportFile(string DownloadToken, string Name, string Type) { //Set DownloadToken Cookie. Response.SetCookie(new HttpCookie("downloadToken", DownloadToken) { Expires = DateTime.UtcNow.AddDays(1), Secure = false }); using (var output = new MemoryStream()) { //get File return File(output.ToArray(), "application/vnd.ms-excel", "NewFile.xls"); } }
-
24.나는 오랫동안이 문제로 고생. 마지막으로 우아한 외부 라이브러리는 여기에 제안 나를 도왔다.
나는 오랫동안이 문제로 고생. 마지막으로 우아한 외부 라이브러리는 여기에 제안 나를 도왔다.
from https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax by cc-by-sa and MIT license
'JQUERY' 카테고리의 다른 글
[JQUERY] 요소의 jQuery 스크롤 (0) | 2020.09.21 |
---|---|
[JQUERY] jQuery를 / 자바 스크립트 : iframe이 내용에 접근 (0) | 2020.09.21 |
[JQUERY] 이 업로드하기 전에 이미지를 미리보기 (0) | 2020.09.21 |
[JQUERY] 자바 스크립트 / jQuery를 DOM 변경 리스너가 있습니까? (0) | 2020.09.21 |
[JQUERY] 자바 스크립트 객체의 배열에 ID를 기준으로 개체를 찾기 (0) | 2020.09.21 |