-
字节流:用于处理二进制数据或不需要进行字符编码转换的场景。
- 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