在一些比较特殊的情况,不允许把内网端口映射到外网,可以是用此方法。通过流的方式把数据通过ServletResponse响应给客户端
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
/**filter转发内网图片*/
@WebFilter(displayName="imgFilter" ,urlPatterns=ImgFilter.FILTERPATH+"*")
public class ImgFilter implements Filter {
protected final static String FILTERPATH = "/img/";
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest )req;
String fileName = getName(request.getServletPath());
if (verif(fileName)) {//验证图片格式
/*
* 转发思路,从数据源获取到流,通过ServletResponse转发给客户端
* 1.在一些比较特殊的情况,不允许把内网端口映射到外网,可以是用此方法
* 如果可以映射到外网使用nginx是个不错的选择
* 测试模拟使用Flle 读取本地文件
*/
File file = new File("D:\\img\\"+fileName);
if (!file.exists()) {
write(response, "404".getBytes());
return;
}
FileInputStream fis;
fis = new FileInputStream(file);
long size = file.length();
byte[] temp = new byte[(int) size];
fis.read(temp, 0, (int) size);
fis.close();
write(response, temp);
}else{
filterChain.doFilter(req, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
/**获取文件名*/
private String getName(String address){
String name = "";
if (FILTERPATH.length() < address.length()) {
name = address.substring(FILTERPATH.length(),address.length());
}
return name;
}
/**验证文件后缀*/
private boolean verif(String name){
int index = name.lastIndexOf(".");
if (index > 0) {
String[] strings = new String[]{"jpg","png"};
for (String string : strings) {
if (string.equals(name.substring(index+1))) {
return true;
}
}
}
return false;
}
/**输出消息*/
public void write(ServletResponse response,byte[] data) throws IOException{
OutputStream out = response.getOutputStream();
response.setContentType("image/jpeg");
out.write(data);
out.flush();
out.close();
}
}