【问题标题】:URL image path showing 404 error显示 404 错误的 URL 图像路径
【发布时间】:2017-07-04 18:19:15
【问题描述】:

我尝试使用以下代码在 img 标记中显示图像,但在浏览器控制台显示 404 文件未找到错误。

Jsp 页面:

<img id="img" src="logo.jsp?path=${schoolModel.user_name}" style="width:105px; height:120px;"/>

logo.jsp:

<%@page import="com.slv.CommonUtils.WebSLCMConstants"%>
<%@page import="java.io.BufferedOutputStream"%>
<%@page import="java.io.BufferedInputStream"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.File"%>
<%@page import="java.io.InputStream"%>
<%
File f=null;
try {
    System.out.println("Inside");
    String path=request.getParameter("path");       
        if(path.equals("")){
            f=new File(WebSLCMConstants.img_retrieve_path+"WebSLCM/no_image.jpg");
        } else {
            f=new File(WebSLCMConstants.img_retrieve_path+path);
        }
        String str=f.toString();
        response.setContentType("image/jpg");
        ServletOutputStream sos;
        FileInputStream fin = new FileInputStream(str);
        BufferedInputStream bin = new BufferedInputStream(fin);
        sos = response.getOutputStream();
        BufferedOutputStream bout = new BufferedOutputStream(sos);

        int ch =0;
        while((ch=bin.read())!=-1)
        {
            bout.write(ch);
        }
        bin.close();
        fin.close();
        bout.close();
        if (true) return;
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
%>

在 GUI 浏览器控制台显示 404 文件未找到错误如下:

]1

【问题讨论】:

  • WebSLCMConstants.img_retrieve_path的值是多少?
  • 我在 logo.jsp 中打印 sop,它没有打印,,它在 src="logo.jsp?paths=${schoolModel.user_name}" 中给出错误

标签: image jsp spring-mvc http-status-code-404


【解决方案1】:

JSP 页面:

<img id="img" src="image.do?path=yourPath" style="width:105px; height:120px;"/>

控制器类:

@RequestMapping(value = "/image.do", method = RequestMethod.GET)
    public ResponseEntity getImage(String path, HttpServletResponse response) {
        try {
            if (StringUtils.isEmpty(path)) {
                return new ResponseEntity(HttpStatus.NOT_FOUND);
            } else {
                response.setHeader("Content-Type", "image/jpg");
                FileInputStream fin = new FileInputStream(path);
                ServletOutputStream out = response.getOutputStream();

                IOUtils.copy(fin, out);
                IOUtils.closeQuietly(fin);

                response.flushBuffer();
                return new ResponseEntity(HttpStatus.OK);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 2015-09-21
    • 2017-08-27
    • 2020-03-19
    • 1970-01-01
    相关资源
    最近更新 更多