response读取图片+下载图片
Posted 小江
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于response读取图片+下载图片的主要内容,如果未能解决你的问题,请参考以下文章
javaweb学习总结二十六(response对象的用法二 下载文件)
java web二进制流的图片如何用response返回给前台