how to display image which is outside server directory in strtus

天大地大妈咪最大 提交于 2019-11-28 06:19:06

问题


This question is continuation to my previous question Accessing External Files Into Our Web Application, actually I am uploading file using struts tag <html:file property="file" />

But now I wanted to show the uploaded images from that location but I am getting src location as http://localhost:9443/D:/resources/images/img1.jpg which is not a valid path for that image.

How to access that image which is outside my server directory.

This is how I am sending Ajax response with Absolute path of images

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);
    }

This is how I am rendering images at 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'>";
        });

but at img tag I am getting image path as http://localhost:9443/D:/resources/images/img1.jpg


回答1:


You can't render images in such way. Web server treated your image path as relative and add qualifying url location on the server. You should create an action to serve images, for example

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

Then render HTML like

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

Now, create the action that write the binary image data to the response output stream. Take a parameter path in the action that let you find a file for binary output. After the flushing output return null so struts should not forward the action further. You could also add headers to turn off a Cache-Control to make sure the images are retrieved from the server.




回答2:


Hi Below is the answer to my question, I have created ImageServlet for displaying image, steps to perform:

1. you need to add mapping in web.xml file:

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

2. create 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. At jsp side you need to add the mapping in step 1 in your img tag i.e. input type='image':

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

You can even create Action class and use execute method for doing the same.



来源:https://stackoverflow.com/questions/19178394/how-to-display-image-which-is-outside-server-directory-in-strtus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!