2

我有一个来自外部 JSP(Second.jsp) 文件的图像。我在 First.jsp 中有我的按钮。当我单击按钮时,应该下载图像。如何通过更改内容类型来做到这一点?

第一个.jsp:

   <div id="first">
      <button id="submit"> Download Image</button>
      <jsp:include page="second.jsp"></jsp:include>
   </div>

第二个.jsp:

    <img alt="Input Voltage" src="/solarether/GraphsServlet?date=<%=date%>&date1=<%=date1%>&siteId=<%=siteID%>&type=<%=type%> height="300" width="600">
4

2 回答 2

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();
}
于 2013-09-23T07:16:09.893 回答
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>
于 2013-09-23T08:47:17.677 回答