【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的路径即可进行显示了

    

 

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

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

 

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

 

你可能感兴趣的:(JavaWeb,IO流,JavaWeb,IO流)