我的jquery下载文件有问题。
我有一个post函数,可以在java代码中发送请求。
我返回文件但是没有下载。
输入
<input type="button" id="export-csv" value="Export result in CSV"/>
Html-jquery Code
$( "#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代码
@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;
}
答案 0 :(得分:1)
如果您不想提交表单,可以在get请求中将此文件写入响应对象: -
@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();
}
在前端,侧面将文件附加到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;
答案 1 :(得分:0)
简单地说,你不能。使用Ajax,由于安全原因,您无法下载文件。您所能做的只是提交表单请求。