【问题标题】:Why are images shown on server but not on localhost?为什么图像显示在服务器上而不显示在本地主机上?
【发布时间】:2020-08-18 14:06:19
【问题描述】:

通过以下 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 属性然后我得到“拒绝访问”)

有什么想法吗?

【问题讨论】:

  • 这是因为 file-delimiter 在 Windows 和服务器中不同吗?
  • 部署服务器是基于 linux 的。我确实尝试了 / 和 \ 的不同组合以尝试解决问题。
  • 只是一个建议 - 您能否在 Windows 部署中将 \ 替换为 \\ ?这实际上导致了我在 Windows 中使用 Python 的问题。
  • 该路径相对于什么 URI? “上传”是否设置为部署(不在默认的WebContent 文件夹下)?
  • @ntind "uploads" 和 "WebContent" 都是上下文根目录的子目录。

标签: html eclipse tomcat localhost


【解决方案1】:

以下内容没有回答为什么本地环境和服务器应该以不同方式工作的问题,但它确实提供了一个可行的解决方案。 (代码基于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();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2019-11-05
    • 2022-10-12
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    相关资源
    最近更新 更多