JSP 如何在Struts中显示服务器目录之外的图像

v8wbuo2f  于 2023-10-14  发布在  其他
关注(0)|答案(2)|浏览(97)

这个问题是我上一个问题Accessing External Files Into Our Web Application的延续,实际上我正在使用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

mfuanj7w

mfuanj7w1#

嗨下面是我的问题的答案,我已经创建了ImageServlet显示图像,步骤执行:

1.需要在web.xml文件中添加Map:

<servlet-name>ImageServlet</servlet-name>
    <url-pattern>/ImageServlet/*</url-pattern>

2.创建ImageServlet

public class ImageServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {

        //Setting image path
        ImageLocationService locationService = new ImageLocationService();

        try {
            String imageCategory = request.getParameter("imageCategory");
            if (imageCategory != null) {
                this.imagePath = locationService.getImageLocation(imageCategory);
            }else{
                this.imagePath = ConfigConstants.imageLocation;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get requested image by path info.
        String requestedImage = request.getPathInfo();

        // Check if file name is actually supplied to the request URI.
        if (requestedImage == null) {
            // Do your thing if the image is not supplied to the request URI.
            // Throw an exception, or send 404, or show default/warning image, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }

        // Decode the file name (might contain spaces and on) and prepare file object.
        File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8"));

        // Check if file actually exists in filesystem.
        if (!image.exists()) {
            // Do your thing if the file appears to be non-existing.
            // Throw an exception, or send 404, or show default/warning image, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }

        // Get content type by filename.
        String contentType = getServletContext().getMimeType(image.getName());

        // Check if file is actually an image (avoid download of other files by hackers!).
        // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
        if (contentType == null || !contentType.startsWith("image")) {
            // Do your thing if the file appears not being a real image.
            // Throw an exception, or send 404, or show default/warning image, or just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }

        // Init servlet response.
        response.reset();
        response.setBufferSize(DEFAULT_BUFFER_SIZE);
        response.setContentType(contentType);
        response.setHeader("Content-Length", String.valueOf(image.length()));
        response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");

        // Prepare streams.
        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
            // Open streams.
            input = new BufferedInputStream(new FileInputStream(image), DEFAULT_BUFFER_SIZE);
            output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

            // Write file contents to response.
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } finally {
            // Gently close streams.
            close(output);
            close(input);
        }
    }

    private static void close(Closeable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                // Do your thing with the exception. Print it, log it or mail it.
                e.printStackTrace();
            }
        }
    }
}

3.在jsp端,你需要在你的img标签中添加第一步中的Map,即:输入类型='image':

<input  type="image" alt='No image found' src='../ImageServlet/append image name that you want to display' />

您甚至可以创建Action类并使用execute方法来执行相同的操作。

aij0ehis

aij0ehis2#

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

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

然后呈现HTML,如

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

现在,创建将二进制图像数据写入响应输出流的操作。在action中输入一个参数path,让您找到一个用于二进制输出的文件。在冲洗输出返回null之后,struts不应进一步转发操作。您还可以添加头来关闭Cache-Control,以确保从服务器检索图像。

相关问题