Java web 封装一个工具类 读取数据响应给浏览器

  1. 字节流:用于处理二进制数据或不需要进行字符编码转换的场景。

    • InputStream:用于从输入源(如文件)读取字节数据。
    • OutputStream:用于向输出目标(如文件)写入字节数据。
OutputStream outputStream = null;
FileInputStream inputStream = null;                   
    outputStream = response.getOutputStream();
    inputStream = new FileInputStream(imagePath);

将代码封装一个工具类

代码展示:

public static void responseImg(String imagePath, HttpServletResponse response) throws IOException {
        OutputStream outputStream = null;
        FileInputStream inputStream = null;
        try {
            outputStream = response.getOutputStream();
            inputStream = new FileInputStream(imagePath);
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            response.setContentType(getContentType(imagePath));
            outputStream.flush();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

 下面展示示例:

通过:WebServlet注解

@WebServlet("/imgC")

 通过该路径:

 效果展示:

 创建一个HTML文件 并实现点击按钮 切换图片:

HTML代码展示:

 <div id="app">
        <img src="/randomImgC" width="400" height="450">
        <button onclick="location.reload()">换一张图片</button>
  </div>

给button按钮设置一个点击事件

后端代码块:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String filename[] = new File("D:\\mysql表\\beauty\\").list();

        String imgName = filename[(int) Math.floor(Math.random() * filename.length)];
        ImgUtil.responseImg("D:\\mysql表\\beauty\\" + imgName, resp);
    }

效果展示:

访问HTML地址:   http://localhost:8081/beauty.html

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值