从servlet中的文件系统提供静态图像文件? [英] Serve a static image file from the filesystem in a servlet?

查看:155
本文介绍了从servlet中的文件系统提供静态图像文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在servlet中为文件系统提供图像文件? > 示例仓库:在Servlet中返回图像 链接破碎。插入下面的Wayback Machine拷贝:

  //这个方法被servlet容器调用来处理一个GET请求。 
public void doGet(HttpServletRequest req,HttpServletResponse resp)throws IOException {
//获取映像的绝对路径
ServletContext sc = getServletContext();
String filename = sc.getRealPath(image.gif);

//获取图像的MIME类型
String mimeType = sc.getMimeType(filename);
if(mimeType == null){
sc.log(无法得到MIME类型的+ filename);
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}

//设置内容类型
resp.setContentType(mimeType);

//设置内容大小
文件文件=新文件(文件名);
resp.setContentLength((int)file.length());

//打开文件并输出流
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();

//将文件的内容复制到输出流
byte [] buf = new byte [1024];
int count = 0; ((count = in.read(buf))> = 0){
out.write(buf,0,count);
}
in.close();
out.close();
}


How do I serve an image file in the filesystem from a servlet?

解决方案

Have a look over here: Example Depot: Returning an Image in a Servlet Link broken. Wayback Machine copy inserted below:

// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Get the absolute path of the image
    ServletContext sc = getServletContext();
    String filename = sc.getRealPath("image.gif");

    // Get the MIME type of the image
    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;
    }

    // Set content type
    resp.setContentType(mimeType);

    // Set content size
    File file = new File(filename);
    resp.setContentLength((int)file.length());

    // Open the file and output streams
    FileInputStream in = new FileInputStream(file);
    OutputStream out = resp.getOutputStream();

    // Copy the contents of the file to the output stream
    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
        out.write(buf, 0, count);
    }
    in.close();
    out.close();
}

这篇关于从servlet中的文件系统提供静态图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆