为什么图像显示在服务器上而不显示在本地主机上?

时间:2020-08-18 14:06:19

标签: html eclipse tomcat localhost

通过以下HTML上传到部署服务器后,图像会正确显示。

<img width="516" height="730" class="theCanvas img-fluid" style="transform-origin: 50% 50%;
transition:transform 200ms ease-in-out; cursor: move; transform: matrix(1, 0, 0, 1, 0, 0);"
draggable="false" src="../uploads/Scans/uploadedImage.jpg">

但是从本地主机(Eclipse,Tomcat)运行应用程序并从那里上载图像时,不会显示该图像。

即使我编辑源代码(通过F12开发工具编辑src标签)也不会显示

http://localhost:8080/contextRoot/uploads/Scans/uploadedImage.jpg

即使我尝试将文件的完整来源提供给Eclipse中的位置,也不会显示

C:\Users\myUser\eclipse-workspace\contextRoot\uploads\Scans\uploadedImage.jpg

(尽管我认为这最后一个问题是由于跨域问题引起的,就像我尝试并使用jquery更改src属性然后得到“访问被拒绝”)

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

以下内容未回答有关本地环境和服务器为何应以不同方式工作的问题,但确实提供了可行的解决方案。 (基于Ali Irawan's solution 的代码)

写一个servlet检索图像,然后使用诸如

之类的代码显示图像
$('#image').attr("src","display?id="+result);

该servlet将在web.xml中定义

 <servlet-name>DisplayServlet</servlet-name> 
     <servlet-class>com.web.DisplayServlet</servlet-class> 
    </servlet>

    <servlet-mapping> 
     <servlet-name>DisplayServlet</servlet-name> 
     <url-pattern>/display</url-pattern> 
    </servlet-mapping>
    <servlet>

该servlet看起来像

public class DisplayServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = -7598483378197199569L;
    

         
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String id = SecurityIssues.paramEncode(request.getParameter("id"));
        response.setContentType("image/jpeg");
        
        String fileFullPath = "C:\exampleDir\" + id + ".jpg";
        
        File my_file = new File(fileFullPath);

        // This should send the file to browser
        OutputStream out = response.getOutputStream();
        FileInputStream in = new FileInputStream(my_file);
        byte[] buffer = new byte[4096];
        int length;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();
    }
}