Java – servlet (SSM、Spring Boot通用) 显示图片

SSM + Vue + Element UI 图片上传 服务器:点我查看

导入所需的jar包

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

编写servlet

在config下创建Image_show.java文件
下面的代码直接copy到上面的文件中即可
访问路径(方法):localhost:8080/image?image=“你的图片名字”

import javax.imageio.ImageIO;
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.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@WebServlet("/image")
public class Image_show extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String image=request.getParameter("image");
            File file;
            BufferedImage im;
            try {
                file = new File("D:/user/" + image);
                im= ImageIO.read(file);
            } catch (Exception e) {
                file = new File("D:/user/1.jpg");
                im=ImageIO.read(file);
            }
            response.setContentType("image/jpeg");
            ServletOutputStream sos=response.getOutputStream();
            ImageIO.write(im, "jpeg", sos);
        } catch (Exception e) {
        }
    }
}
未分类>
匿名

发表评论

匿名网友