jfinal-4.2 定义render 返回图片文件 在html上可以使用image标签展示
ContentTypeKit图片类型
package com.litong.jfinal.render; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * ContentType */ public class ContentTypeKit { public static Map<String, String> map = new ConcurrentHashMap<String, String>(); static { map.put("jpeg", "image/jpeg"); map.put("jpg", "image/jpeg"); map.put("jpe", "image/jpeg"); map.put("png", "image/png"); } public static String get(String mimetype) { String string = map.get(mimetype); return string; } }
MimeTypeRender 自定义render
package com.litong.jfinal.render; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.servlet.ServletOutputStream; import com.jfinal.render.Render; import lombok.extern.slf4j.Slf4j; /** * 用来render输出图片到浏览器 */ @Slf4j public class MimeTypeRender extends Render { private String exName; private String filename; private boolean isDwoload; public MimeTypeRender(String exName, String filename) { this.exName = exName; this.filename = filename; } public MimeTypeRender(String exName, String filename, boolean isDwoload) { this.exName = exName; this.filename = filename; this.isDwoload = isDwoload; } public void render() { File file = new File(filename); if (!file.exists()) { String msg = "file not exists:" + file.getAbsolutePath(); log.info(msg); try { response.getWriter().print(msg); } catch (IOException e) { e.printStackTrace(); } return; } // 设置头信息,内容处理的方式,attachment以附件的形式打开,就是进行下载,并设置下载文件的命名 if (isDwoload) { response.setHeader("Content-Disposition", "attachment;filename=" + file.getName()); } response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType(ContentTypeKit.get(exName)); ServletOutputStream sos = null; try { sos = response.getOutputStream(); // 创建文件输入流 FileInputStream is = new FileInputStream(file); // 创建缓冲区 byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { sos.write(buffer, 0, len); } is.close(); } catch (Exception e) { log.error("图片render出错:" + e.getLocalizedMessage(), e); throw new RuntimeException(e); } finally { if (sos != null) try { sos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
在Contrller中调用测试
package com.litong.jfinal.controler; import com.jfinal.core.Controller; import com.litong.jfinal.render.MimeTypeRender; public class ImageController extends Controller { public void index() { MimeTypeRender mimeTypeRender = new MimeTypeRender("jpg", "head.jpg"); render(mimeTypeRender); } }
在浏览器中测试访问
访问成功