gpt4 book ai didi

java - 如何让用户以ajax成功方法下载文件?

转载 作者:行者123 更新时间:2023-11-30 11:26:35 25 4
gpt4 key购买 nike

我正在尝试让用户从服务器下载文件。我在我的 Controller 中使用 ServletOutputStream(这里是代码)

@RequestMapping(value = "/get-backup-file", method = RequestMethod.GET)
@ResponseBody
public void getBackupFile(
HttpServletRequest request,
HttpServletResponse response) throws MalformedURLException, IOException {

File backupFile = new File("PATH_TO_FILE");

ServletOutputStream out = response.getOutputStream();

response.setContentType("application/octet-stream");
response.setContentLength((int)backupFile.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + "database backup" + "\"");

FileInputStream in = new FileInputStream(backupFile);
byte[] buffer = new byte[4096];

int length;
while( (length = in.read(buffer) ) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
}

我的客户端是这样的:

      $.ajax({
url: 'URL_TOCONTROLLER_METHOD',
contentType: "application/octet-stream; charset=utf-8",
type: 'GET',
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("error");
}
});

当我 console.log 数据时,它具有文件的内容,但我希望用户下载该文件,而不仅仅是打印。如何让用户将数据保存为文件?

最佳答案

你必须发送文件存储的路径并打开它的成功功能,然后用户才能下载它

如果成功就是这样

{"status":"success","path":"temp\/Vehicle_Units_2013_11_04.xls"}

脚本是

success: function(msg)
{
if(msg.status=="session-expired")
{
window.location.replace("index.jsp");
}
if(msg.status=="success")
{
window.open(msg.path);
}

}

关于java - 如何让用户以ajax成功方法下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19765566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com