当用户单击按钮时,就会对服务器进行 ajax 调用。服务器返回一个文本文件。 我希望浏览器自动下载文件。
.jsp button
<button type="submit" id="btn_load" value="Search" class="btn btn-primary">Generate I-618</button>
.js file - when button is click
$("#btn_load").click(function(e) {
event.preventDefault();
form = $('#bookList');
var post_url = form.attr("action");
let form_data = form.serialize();
$.ajax({
url: post_url,
type: "POST",
data: form_data,
success: function(data, textStatus, jqX) {
// **data is a .txt file. HOW DO TELL BROWSER TO DOWNLOAD THE FILE ?**
console.log(data); //print the data from the file
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
});
java:函数返回一个 .text 文件,当用户单击按钮时要从浏览器下载该文件
@RequestMapping(value = "/book.htm")
public ResponseEntity<InputStreamResource> bookselection(
@ModelAttribute("books") Books book, Model model,
HttpServletRequest request, BindingResult result) {
List<InputStreamResource> listStream = new ArrayList<InputStreamResource>();
String fileName = "book.txt"
if (CollectionUtils.isNotEmpty(bookList)) {
File file = File.createTempFile(fileName, ".txt");
FileWriter interfaceFileWriter = new FileWriter(file);
BufferedWriter interfaceBufferedWriter = new BufferedWriter(interfaceFileWriter);
//write to file
for (Book list : bookList) {
interfaceBufferedWriter.write(list.getDelimitedRecord(delimiter, nullValue));
}
interfaceBufferedWriter.close();
HttpHeaders headers = new HttpHeaders();
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
headers.setContentDispositionFormData(fileName + ".txt", fileName + ".txt");
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
if (file != null && file.exists()) {
listStream.add(resource);
return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).headers(headers).body(resource);
}
}
return null;
}
如何告诉浏览器自动下载文件,即ajax响应(数据)?
要触发自动下载文件以响应 AJAX 调用,您可以动态创建具有下载属性的链接并触发对该链接的单击。您可以通过以下方法修改成功回调来实现此目的:
$("#btn_load").click(function (e) {
event.preventDefault();
form = $("#bookList");
var post_url = form.attr("action");
let form_data = form.serialize();
$.ajax({
url: post_url,
type: "POST",
data: form_data,
success: function (data, textStatus, jqX) {
// Create a Blob from the data
var blob = new Blob([data], { type: "text/plain" });
// Create a link element
var link = document.createElement("a");
// Set the download attribute and create a URL for the file
link.download = "your_filename.txt";
link.href = window.URL.createObjectURL(blob);
// Append the link to the document
document.body.appendChild(link);
// Trigger a click on the link to initiate the download
link.click();
// Remove the link from the document
document.body.removeChild(link);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// Handle errors
},
});
});
此代码根据 AJAX 响应中收到的数据创建一个
Blob
,创建一个链接元素,设置 download
属性和文件的 URL,将链接附加到文档,触发对链接的单击,然后最后从文档中删除链接。
确保将
'your_filename.txt'
替换为下载文件所需的文件名。