通过response把本地图片输出到浏览器

  • Post author:
  • Post category:其他


package send2;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/sendServlet2")
public class sendServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

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


//        获得图片的绝对路径
        String path = getServletContext().getRealPath("man.jpg");
        System.out.println(path);
//        获取本地字节输入流
        FileInputStream fis = new FileInputStream(path);
//        获取本地字节输出流
        ServletOutputStream out = response.getOutputStream();
        int len=0;
//        建立一个数组 一次读1024个字节
        byte[] bytes = new byte[1024];
        while ((len=fis.read(bytes))!=-1){
            out.write(bytes,0,len);
        }
        fis.close();

        //        中文显示格式
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("祖国万岁 我是send2");


    }
}



版权声明:本文为qq_45112637原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。