[英]Download File By jquery from java
i Have a problem with download file by jquery.我在通过 jquery 下载文件时遇到问题。
I have a post function that send request in the java code.我有一个 post 函数,可以在 java 代码中发送请求。
I return the file but this doesn't download.我返回文件,但这不会下载。
Input输入
<input type="button" id="export-csv" value="Export result in CSV"/>
Html-jquery Code html-jquery 代码
$( "#export-csv" ).click(function( ) {
var request=$.ajax({
method: "POST",
url: 'user/writeCsv',
data: $( "#search-form" ).serialize(),
dataType: "text/csv"
}).done(function(data) {
window.location.href = (data);
});
// $.post( "user/writeCsvToReturn", $( "#search-form" ).serialize())
});
Java code Java代码
@RequestMapping(value="/user/writeCsv",method=RequestMethod.POST)
public FileWriter writeCSVFile(HttpServletResponse response,ServerSearchCommand ssc, Model model, BindingResult result) throws IOException {
FileWriter fileWriter= new FileWriter("/tmp/searchcsv.csv");
fileWriter.flush();
//WRITE DATA FILE
fileWriter.close();
return fileWriter;
}
If you don't want to submit form , you can have this work around write the file in response object in get request:-如果您不想提交表单,您可以在获取请求中将文件写入响应对象中:-
@RequestMapping(value="/user/writeCsv",method=RequestMethod.Get)
public void writeCSVFile(HttpServletResponse response,ServerSearchCommand ssc, Model model, BindingResult result) throws IOException {
OutputStream outStream = response.getOutputStream();
// Write data to this outStream
outStream.close();
}
On front end , side append file to iFrame and make iFrame stye = display:none :-在前端,侧面将文件附加到 iFrame 并使 iFrame stye = display:none :-
var url = contextPath + "/user/writeCsv";
var hiddenIFrameID = 'frameid',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
Simply you cannot.只是你不能。 With Ajax you cannot download a file due to security reasons.
由于安全原因,使用 Ajax 无法下载文件。 All you can do is a submit a form request.
您所能做的就是提交表单请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.