我有一个来自外部JSP(Second.jsp)文件的图像。我在First.jsp中有我的按钮。当我点击按钮时,应该下载图像。如何通过更改内容类型来实现?
First.jsp:
<div id="first">
<button id="submit"> Download Image</button>
<jsp:include page="second.jsp"></jsp:include>
</div>
Second.jsp:
<img alt="Input Voltage" src="/solarether/GraphsServlet?date=<%=date%>&date1=<%=date1%>&siteId=<%=siteID%>&type=<%=type%> height="300" width="600">
答案 0 :(得分:1)
单击下载按钮调用servlet并在流中设置响应文件..文件将下载。用doGet或doPost方法实现代码
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
File file = new File(filePath);
int length = 0;
ServletOutputStream outStream = response.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType(filePath);
// sets response content type
if (mimetype == null) {
mimetype = "application/octet-stream";
}
response.setContentType(mimetype);
response.setContentLength((int)file.length());
String fileName = (new File(filePath)).getName();
// sets HTTP header
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
byte[] byteBuffer = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(file));
// reads the file's bytes and writes them to the response stream
while ((in != null) && ((length = in.read(byteBuffer)) != -1))
{
outStream.write(byteBuffer,0,length);
}
in.close();
outStream.close();
}
答案 1 :(得分:0)
也许你需要js: Jsp应该这样:
<div id="first">
<button id="submit"> Download Image</button>
<jsp:include page="second.jsp"></jsp:include>
<script>
$("#submit").click(function(){
window.location.href=$(this).siblings("img").attr("src");
})
</script>
</div>