减小网络传输图片大小,使用gzip进行压缩

package com.servlet; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.zip.GZIPOutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author */ public class ShowImageServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 5449572787413228295L; public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doProcess( request, response ); } public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doProcess( request, response ); } public void doProcess( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String param = getInitParameter( "requestParam" ) == null ? "name" : getInitParameter( "requestParam" ); String imagePath = getInitParameter( "imagePath" ) == null ? "images" : getInitParameter( "imagePath" ); String name = request.getParameter( param ); OutputStream out; if ( (isGzipSup( request )) ) { out = (new GZIPOutputStream( response.getOutputStream() )); response.setHeader( "Content-Encoding", "gzip" ); } else { out = response.getOutputStream(); } FileInputStream fin = new FileInputStream( this.getServletContext().getRealPath( "/" ) + imagePath + "/" + name ); byte[] buf = new byte[1024]; int num; while ( (num = fin.read( buf )) != -1 ) { out.write( buf, 0, num ); } fin.close(); out.close(); } public boolean isGzipSup( HttpServletRequest request ) { String encoding = request.getHeader( "accept-encoding" ); return ((encoding != null) && (encoding.indexOf( "gzip" ) != -1)); } }

你可能感兴趣的:(减小网络传输图片大小,使用gzip进行压缩)