【JavaWeb】实现读取本地服务器路径下的图片

 Servlet层代码:

package com.ysw.demo;

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("/photo2")
public class PhotoServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取图片的绝对路径
        String path = this.getServletContext().getRealPath("images/photo.jpg");
        //输出测试一下路径
        System.out.println(path);

        //使用路径创建输入流
        FileInputStream in = new FileInputStream(path);

        //创建一个输出流到浏览器
        ServletOutputStream out = response.getOutputStream();

        int length = 0;
        byte[] buffer = new byte[1024];
        while ((length = in.read(buffer)) != -1){
            out.write(buffer);
        }
        in.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

前端只需要指定一个img的路径即可进行显示了

    <img src="photo2" width="100px" height="100px">

 

这里使用IDEA环境的话,一定要记得配置IDEA的服务器到Tomcat的WebApp目录下,详情如图所示:

 

小编这边图片的绝对路径是:D:\apache-tomcat-8.5.31\webapps\practice\images\photo.jpg

 

发布了17 篇原创文章 · 获赞 13 · 访问量 569
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览