I have a Struts2 액션 파일 서버 측 다운로드하십시오.
<action name="download" class="com.xxx.DownAction">
<result name="success" type="stream">
<param name="contentType">text/plain</param>
<param name="inputName">imageStream</param>
<param name="contentDisposition">attachment;filename={fileName}</param>
<param name="bufferSize">1024</param>
</result>
</action>
그러나 내가 security. 사용하여 동작을 포함한다.
$.post(
"/download.action",{
para1:value1,
para2:value2
....
},function(data){
console.info(data);
}
);
내가 보고 있는 방화범 읽어들여집니다 이진 데이터 스트림을 통해 . 제가 생각하기엔 여는 방법 파일 다운로드 창 파일을 저장할 수 있는 사용자 로칼에서?
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 거짓값 바벨. > 거짓값 -;
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
// the filename you want
a.download = 'todo-1.json';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
alert('your file has downloaded!'); // or you know, something with better UX...
})
.catch(() => alert('oh no!'));
끝 - < 스니핏 >;!
등으로 은 완전히 맞았어, 아약스는 이 전날에약혼자에게 can& t do it 통해 JavaScript 파일을 저장할 수 있기 때문에 # 39 에 직접 user& # 39 의 컴퓨터 (아웃해야 보안상 숙정문). , # 39 의 기본 window& 향하고 죄송합니다. uirl 시 사용자 환경은 다운로드창이 뜻입니다 리틀이에요 제어입니다 락하였으니 다운로드창이 때 발생합니다.
내가 만든 수 있는 jQuery 다운로드창이 에 대해, 아약스는 " like". 경험이 있는 더 나은 사용자 경험을 제공하기 위해, 파일 다운로드 및 OnFailure 콜백 완료하십시오 OnSuccess. Take a look at my 블로그 포스트 에 일반적인 문제를 해결할 수 있는 플러그인 사용 방법 또한, 일부 정보기술 (it) 과 데모 jquery 다운로드창이 실천. 다음은 출처
다음은 출처 를 사용하여 간단한 览侩 荤례 데모 플러그인에는 그렇다. 다른, & # 39 의 데모 페이지 # 39 더 많이 포함되어 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 다운로드창이 /dev/raw/raw1 포함한다.
window.location="download.action?para1=value1...."
[1]: https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax # comment4981707_4545311
NB: 이진 데이터를 JSON 데이터 파일을 변경할 수 없기 때문에 인코딩합니다 반환되었습니다 base64 인코딩되지 있어야 합니다.
내 '아약스의 응답 (i have a 데이터 구조는 다음과 같습니다.
{
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);
}
1 및 [here] 에서 만든 함수를 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});
};
이런 현상은 서버에 저장할 수 있는 경우 필드라타 덤프하는 있다. 그러나 한 것도 아니고, 대체 어떻게 구현할 것이라고 HTML4 협력했습니다 아웃해야 I& # 39
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>
사용할 수 있는 게 좋을 것 같다 ',' 로근발 <, s:a> 태그번호 가리키는 URL 로 만든 ',' s:url> 충족되었으며 <, 태그:
<!-- 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 와 (사용하지 않는 한 작업 비호환성의 서브렛 문제지고 해킹 [직접판매용 스티리밍] (https://stackoverflow.com/a/16654313/1654265), 예를 들어 경우), t need to # 39 don& 아무것도 준비하지 직접 대응에. 단순히 name. domain. [스트리밍합니다 결과 유형이] (http://struts.apache.org/release/2) 에서 이를 스트라우츠.1믈 .3.x/struts2-core/apidocs/org/apache/struts2/dispatcher/streamresult.html) 및 구성인텔 작동합니다. [예] (http://www.mkyong.com/struts2/struts-2-download-file-example/)
<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 레임워크): 브라우저 내에 파일 열기 서브렛 (/ Action)
스케쳐내 파일을 열 수 있는 브라우저, 인라인 컨텐츠 폐기입니다 다운로드하십시오 대신 이 설정해야 합니다 하지만 타겟대상 can& # 39, t be 현재 창 위치. javascript 가 만든 새 창을 공략하십시오 합니다 ',' 를 즉석에서 만든 iframe> <, 페이지 또는 새 창을 통해 discussed" "; target = " _blank";:
<!-- 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>
내가 hotenough. 리틀이에요 역할을 해결하십시오 솔루션 (영감을 @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');
});
이 파일은 간단하게 할 수 있는 브라우저 다운로드 요청을 할 수 있는 것을 좋아한다.
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();
}
이 브라우저는 팝업 열었든 다운로드하십시오.
내가 이 같은 문제를 겪고, 성공적으로 해결했다. 내 활용 로만스였나.
json 데이터를 받을 경우,, < " i> 게시물로의 서버와 일치해야 합니다. 서버에서 클라이언트에 대한 응답으로 반환함 있는 엑셀 파일이 생성됩니다. 사용자 정의 이름을 함께 있는 다운로드하십시오 응답 파일로 browser< /i> ";;
$("#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));
});
위의 단편이 할 일을 한 다음
Here we need to 몇 가지 주의 깊게 설정되었습니다 서버 측에서. I set 의 몇 헤더도 파이썬 장고 하테프레스폰지. 다른 프로그래밍 언어에서 사용하는 경우 적절하게 설정해야 합니다.
# In python django code
response = HttpResponse(file_content, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
여기서, 제가 하도 다운로드하십시오 xls (excel) 이상 조정된 콘텐티페 하나. 이 파일 형식에 따라 설정해야 합니다. 모든 종류의 파일을 다운로드할지 이 기술을 사용할 수 있습니다.
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});
});
이 같은 params 전송되므로 이벤트수정적절한 게시물로의 params 오는 것처럼 입력 아닌 json 인코딩되지 구체화하십시오 따라 이전 예제에서와.
경고: 대한 잠재적 변수 (variable) 혹은 경계해야 사람들에 대해 말한다. 이러한 com/go/4e6b330a_kr 인코드할 안전한 방법이 있을 수 있습니다. 또는 탈출이라니요 저들이요 볼
이것은 무엇을 했는지, 순수 javascript 와 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");
});
>. 그냥 구성 요소를 사용하는 모든 브라우저에서 더 이상 사용할 수 있습니다 >. 라이브러리보다는.
enter 이미지 여기에 설명을! enter 이미지 여기에 설명을!
>. 이것은 나의 봄 컨트롤러거 서버측 자바 코드를.
@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();
}
}
}
의 레일, 나는한다 it this way.
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));
}
});
}
, # 39 는 부분) 이 이 트릭 빈다우드로카션 controller& srdf/s 방법은 다음과 같습니다.
# GET /files/{:id}/download_file/
def download_file
send_file(@file.file,
:disposition => 'attachment',
:url_based_filename => false)
end
function downloadURI(uri, name)
{
var link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();
}
좀 더 이상 추가 셨으며 문제에 대한 파일 다운로드
다음은 일부 java 바이트 코드를 생성하는 어레이입니다 봄
@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);
}
아래 코드를 사용하여 javascript 코드를 피레스버리제스 있는 파일을 다운로드할 수 있는 지금,
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);
위의 는 파일 다운로드
여기서는 확인 작업 코드 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);
}
문의 후, 다운로드 및 내려받습니다 " success" 컨트롤러입니다 수 있습니다. 또는 " failure"; 콜백하는
$.fileDownload(mvcUrl('name of the controller'), {
httpMethod: 'POST',
successCallback: function (url) {
//insert success code
},
failCallback: function (html, url) {
//insert fail code
}
});
실제로 사용하지 않고 있는 반면 찾았다고 수리입니다 it& # 39 의 않니다 ajax call to get a javascript 를 사용할 수 있습니다 다음 요청할 때 실제로 다운로드하십시오 콜백하는 다운로드하십시오 시작됩니다. 이 경우 서버 사이드 스크립트 https://partner. 런입니다 도움됐네 i found a little bit 작성하는 데 필요한 파일을 전송하기 전에. # 39 의 처리 및 it& 경고마다 수 있도록 그 때 보라그들은 않니다 마지막으로 파일을 전송하는 것을 제거하여 프로세성 통지용. 그래서 제가 그들이성년에 시도하시려면 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>
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
'작업' () '' 제세르프레트레스폰지 액세스하려면 세르프레트레스폰지아와르 구현할 수 있습니다.
Ajax 호출을 통해 분명한 것은 이 일을 하지 않을 수 있습니다.
그러나 해결 방법이 있습니다.
단계만으로
파일 다운로드 포르마리서브미스 () 를 사용하는 경우, 당신이 무엇을 할 수 있다.
이렇게 하면 여부를 결정할 때 로켈이 운영까지도 후 파일을 다운로드할 수 있도록 하는 포르마리서브미스 (), 예: 포르마리서브미스 예외가 있을 수 있습니다 () 의 경우, 서버 측에서 테스트타사의 대신 사용자 지정 메시지 및 측면 충돌, 표시하십시오 클라이언트상의 할 수 있습니다, 이러한 경우 이 구축상의 도움이 됩니다.
'사용' 빈다우지오픈 https://developer.mozilla.org/en-US/docs/Web/API/Window/open
예를 들어, 이 노선은 처리기에서 의 코드 를 올릴 수 있습니다.
window.open('/file.txt', '_blank');
또 새 탭 열기 (& # 39 슬픔으로창백해지고 _blank& # 39;; 탭 창 이름), 그리고 그 url 이 열립니다.
또한 다음과 같은 네 서버측 코드에서 뭔가를해야합니다 합니다.
res.set('Content-Disposition', 'attachment; filename=file.txt');
브라우저는 사용자가 파일 저장 및 이쪽요 /dev/raw/raw200 프롬프트합니다 디스크 파일, 그 대신 보여줄 뿐이다. 또한 자동으로 있는 탭을 닫으십시오 그냥 문을 열었다.
ajax 의 웹 페이지에 다운로드할지 솔루션이므로 또 있다. 하지만 나는 먼저 처리할 수 있는 페이지를 참조하여 그리곤요 다운로드됨.
첫 페이지를 프로세싱용으로 분리하십시오 합니다 결과에서 다운로드하십시오.
< pre>; $ 스포스트 (" CalculusPage.php" {칼쿨루스풍크션:;; 참, 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;
}
}
);
// 예를 들면 다음과 같습니다. 칼쿨루스팔레스피프 있는
if ( !empty($_POST["calculusFunction"]) )
{
$ID = $_POST["ID"];
$query = "INSERT INTO ExamplePage (data1, data2) VALUES ('".$_POST["data1"]."', '".$_POST["data2"]."') WHERE id = ".$ID;
...
}
// 예를 들면 다음과 같습니다. 다운로드 페이지그프프 있는
$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");
...
< /pre>;
이 솔루션은 날 위해서라고요 때문에 많은 이들에게 도움이 될 수 있기를 바란다.
나는 오래 전부터 이 문제로 어려움을 겪었다. 마지막으로 우아한 외부 라이브러리 제안됩니다 [here] (https://github.com/axios/axios/issues/1660 # issuecomment-404858057) 는 나를 데리고.