1. js代码
注意:调用文件下载接口时,不要使用ajax。使用ajax会导致浏览器的下载功能无法正常触发。因此,我们使用JavaScript的表单模板进行接口调用和数据提交。
$(function () {
$('#fileDownload').click(function () {
//后台方法、文件类型、文件名
downloadTemplate('/fileDownload', 'filename', 'test');
});
});
function downloadTemplate(action, type, value){
var form = document.createElement('form');
document.body.appendChild(form);
form.style.display = "none";
form.action = action;
form.id = 'pdf';
form.method = 'post';
//隐藏标签,可以存放想要传递的参数
// var newElement = document.createElement("input");
// newElement.setAttribute("type","hidden");
// newElement.name = type;
// newElement.value = value;
// form.appendChild(newElement);
form.submit();
}
2. java代码
@RestController
public class FileDownloadController {
@PostMapping("fileDownload")
public void fileDownload(HttpServletRequest request, HttpServletResponse response){
String fileUrl = "static/pdf/SpringCloudDalston.pdf";
String serverUrl = "http://localhost:9097";
// String fileName= fileid.substring(fileid.lastIndexOf("/") + 1);
String fileName = "123.pdf";
String filePath = serverUrl + "/" + fileUrl;
HttpURLConnection urlConn = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//调用文件服务器的地址,获取其输入流
URL url = new URL(filePath);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
InputStream inputStream = urlConn.getInputStream();
//将输入流中获取到的数据通过输出流输出
if (inputStream != null) {
bis = new BufferedInputStream(inputStream);
bos = new BufferedOutputStream(response.getOutputStream());
//设置响应头
//attachment下载
response.setHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes(),"ISO8859-1"));
//类型pdf
response.setContentType("application/pdf");
int readlen = 0;
byte[] buffer = new byte[1024];
while ((readlen = bis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, readlen);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(null!=bos){
bos.close();
}
if(null!=bis){
bis.close();
}
urlConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}