首页 > email中的图片无法显示

email中的图片无法显示

使用JavaMailSender发送邮件,邮件内容采用Velocity作为模板,在内容中包含图片,如果采用访问静态资源的方式直接将图片放到工程目录下,即可访问,代码如下:

<img src="http://localhost:8080/myproject/resource/image/logo.jpg"/>

但如果采用http请求后台读取文件,并将文件写入到response输出流的方式,则无法显示,具体代码如下:
模板代码:

<img src="http://localhost:8080/myproject/get/pic/${imageId}"/>

后台代码:

public void getPic(@PathVariable Long imageId, HttpServletResponse response) {
    try {
        response.setContentType("image/jpg");
        response.addDateHeader("Expires", new Date().getTime() + 60 * 60 * 1000L);
        File file = 通过imageId查询数据库,获取文件
        writeInputStreamToOutputStream(new FileInputStream(file), response.getOutputStream());
    } catch (IOException e) {
        // ignore
    }
}

public void writeInputStreamToOutputStream(InputStream inputStream,
            OutputStream outputStream) throws IOException {
    OutputStream out = null;
    InputStream in = null;
    try {
        in = new BufferedInputStream(inputStream, BUFFER_SIZE);
        out = new BufferedOutputStream(outputStream, BUFFER_SIZE);
        byte[] buffer = new byte[BUFFER_SIZE];
        int i;
        while ((i = in.read(buffer)) != -1) {
            out.write(buffer, 0, i);
        }
    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e) {
            // ignore
        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
            // ignore
        }
    }
}

哪位大牛可以帮忙解释一下为什么吗?或者指出我使用中的问题所在,多谢


先不说代码。一般发邮件是发链接出去,而不是输出流。
比如图片是放到你的服务器或者独立文件服务器都可以,只有可以有地址可以访问,就像http://localhost:8080/myproject/resource/image/logo.jpg一样。当然,将这个连接放到html模板发送出去。

【热门文章】
【热门文章】