我编写了 JAX-RS 服务,用于使用 apache 服务器下载文件:
服务的主要内容是-
@GET
@Produces("application/pdf")
public Response convertCtoF() {
String path = "D:\a.pdf";
File file=new File(path);
ResponseBuilder rb = Response.ok((Object) file);
rb.header("Content-Disposition","attachment; filename=a.pdf");
return rb.build();
}
当我通过网络浏览器访问它时,这是有效的。
但是当我通过XMLHTTPRequest访问时,它不起作用。它给出 XMLHttp.Status=0
客户端代码:
<!DOCTYPE html>
<html>
<head>
<script>
function Download()
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open('GET','http://localhost:8080/RESTExample/ABC/ctofservice',true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert('xmlhttp.readyState == 4');
if ( xmlhttp.status == 200) {
alert('xmlhttp.status == 200');
}
else
{
alert(xmlhttp.status);
}
}
}
}
</script>
</head>
<body>
<h2>File Downloading Web Interface</h2>
<div id="myDiv"></div>
<button type="button" onclick="Download()">Download File</button>
</body>
</html>
它不适用于XMLHTTPRequest,因为您正在下载文件,并且出于安全原因,您不允许使用Ajax执行此操作。有各种解决方法可以尝试。我不会在这里重复这些,所以尝试在谷歌上搜索"ajax文件下载",然后选择你喜欢的方法。