当我点击链接时,我想在我的“JobDownload”servlet中调用我的API,并将响应作为文件下载到浏览器中。 API返回一个多部分响应,我将其转换为输入流。我可以在下面的console.log()中调用servlet后显示返回的内容,但无法打开浏览器下载框。
我这样称呼:
$("#filename").click(function(){
alert("Download initiated");
$.get('jobDownload', {'key': jobDownId,'name':jobFileName},
function (data) {
console.log("Data Downloaded"+data);
});
});
我的servlet看起来像这样:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String jobId = request.getParameter("key");
String fileName = request.getParameter("name");
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader(headerKey, headerValue);
response.setContentType("text/plain");
System.out.println("\n\nJob ID is :"+jobId+"\nFilename is :"+fileName);
// Calling my API which will return an InputStream
InputStream jobResult = getJobResultById(jobId);
OutputStream os = response.getOutputStream();
System.out.println("\n\nInputStream of job is here");
// Stream the inputStream to outputStream
streamOutput(jobResult, os);
System.out.println("\n\nOutStream of job is here");
}
我的streamOutput方法是这样的:
public void streamOutput(InputStream is, OutputStream os) {
BufferedInputStream dis = null;
try {
dis = new BufferedInputStream(new DataInputStream(is));
byte[] buf = new byte[8192];
int nread = dis.read(buf);
while (nread != -1) {
os.write(buf, 0, nread);
nread = dis.read(buf);
}
// flush the output as soon as possible to prevent client timeouts
// we can delay cleaning up the inputstream
os.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
dis = null;
}
我没有得到用户应该点击下载此结果的浏览器下载对话框。我是否需要在Jquery方法中添加任何内容或在我的java代码中添加内容