通过更改JSP中的内容类型来下载图像

时间:2013-09-23 07:11:00

标签: html jsp mime-types content-type

我有一个来自外部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">

2 个答案:

答案 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>