response读取图片+下载图片

读取图片

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class OutServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

                  String url = this.getContext().getRealPath("test.jpg");
                  InputStream in = new FileInputStream(url);
                  OutputStream out = response.getOutputStream();
		  byte [] by = new by[1024];
                  int i = 0;
                  while((i=in.read(by))!=-1)
                 {
                      
                         out.write(by,0,i);

                  }
                   in.close();
	
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request,response);
	}

}
                      

 下载图片

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class OutServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

//写入请求头下载图片文件
            
 responst.setHeader("Content-Disposition","attachment;filename=test.jpg");

   
    
		
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request,response);
	}

}

 

可以使用

URLEncoder.encode("String","utf-8");   把一个String转成UTF-8

URLDecoder.decode("String","utf-8");   把一个String 解析成UTF-8

可以使用上面方法来给图片文件设置名称,

response.setHeader("Content-Dispostion","attachment;filename="+URLEncoder.encoder("测试.jpg","utf-8"));

 

常用的几种response输出数据格式(不乱码)

   ①

      response.setContentType("text/html;charset=utf-8");    // 告诉用UTF-8解析

      response.setCharacterEncoding("utf-8");    // 告诉服务器用UTF-8 解析

      response.getWriter().write("中国");

   

   ②

      response.setContenType("text/html;charset=utf-8");  // 告诉用UTF-8解析

      response.getOutputStream().write("中国".getBytes("UTF-8"));  // 浏览器用UTF-8解析

   

   ③

       response.getOutputStream().write("中国".getBytes());     //按照浏览器默认的编码解析

 

          日期:2018/05/21

posted @ 2018-05-21 21:24  小江。  阅读(5047)  评论(0编辑  收藏  举报