小编典典

如何显示strtus服务器目录之外的图像

jsp

这个问题是延续我刚才的问题访问外部文件到我们的Web应用程序,实际上我使用Struts标签上传文件<html:file property="file" />

但是现在我想显示从该位置上传的图像,但是我正在获取src位置,因为http://localhost:9443/D:/resources/images/img1.jpg该位置不是该图像的有效路径。

如何访问服务器目录之外的映像。

这就是我发送带有图像 绝对路径 的Ajax响应的方式

public ActionForward getAjaxUploadedFiles(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {

        String imagePath = "D:/resources/images/";
        ArrayList<String> path = new ArrayList<String>();

        File imageFile = new File(imagePath);
        File imageFiles[] = imageFile.listFiles();

        for (int i = 0; i < imageFiles.length; i++) {
            path.add(imageFiles[i].getAbsolutePath());
        }

        PrintWriter out = response.getWriter();
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        response.setStatus(HttpServletResponse.SC_OK);

        StringBuffer strXMl = new StringBuffer();
        strXMl.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        strXMl.append("<start>");


        for (String imagePth : path) {
            strXMl.append("<imagePath>");
            strXMl.append(imagePth);
            strXMl.append("</imagePath>");
        }

        strXMl.append("</start>");

        if(strXMl != null){ 
            String Xml = strXMl.toString();
            out.write(Xml);
            System.err.println("XMl Reponse is: " + Xml);
        }
        else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
        out.flush();

        return mapping.findForward(null);
    }

这就是我在JSP上渲染图像的方式

 $(response).find("imagePath").each(function() {
            row = tblReportList.insertRow(0);
            row.className="TableBordergray";
            row.style.width="100%";

            var imagePath = $(this).text();

            cell = row.insertCell(0);
            cell.innerHTML="<img src='" + imagePath + "' alt='" + imagePath + "' height='42' width='42'>";
        });

但在img标签我得到图像路径为http://localhost:9443/D:/resources/images/img1.jpg


阅读 277

收藏
2020-06-08

共1个答案

小编典典

您不能以这种方式渲染图像。Web服务器将您的图像路径视为相对路径,并在服务器上添加合格的URL位置。您应该创建一个操作来投放图片,例如

<action path="/image" ... scope="request" validate="false"/>

然后像

cell.innerHTML="<img src='" + '/image?path=' + imagePath + "' alt='" + imagePath + "' height='42' width='42'>";

现在,创建将二进制图像数据写入响应输出流的操作。path在操作中采用一个参数,该参数可让您找到用于二进制输出的文件。在冲水输出返回后null,支撑杆不应再继续执行该操作。您还可以添加标题以关闭Cache- Control,以确保从服务器检索到图像。

2020-06-08