Java 怎么在servlet中返回图像

2019年8月17日22:07:26 评论 24

1.简介

Java 怎么在servlet中返回图像?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ServletContext sc = getServletContext();
    String filename = sc.getRealPath("image.gif");

    String mimeType = sc.getMimeType(filename);
    if (mimeType == null) {
        sc.log("Could not get MIME type of "+filename);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    resp.setContentType(mimeType);

    File file = new File(filename);
    resp.setContentLength((int)file.length());

    FileInputStream in = new FileInputStream(file);
    OutputStream out = resp.getOutputStream();

    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
        out.write(buf, 0, count);
    }
    in.close();
    out.close();
}

 

3.总结

示例代码演示了 Java 怎么在servlet中返回图像,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: