根据文件可用性在 jsp 页面中下载的动态图像



我在谷歌表格中有一个下载链接:

'<a href="<%= FilePath%>" height="20" width="20" download/><img src="/img/download.png" alt=" Image " title="Click to download" height="20" width="20" /></a>',

其中文件路径可以是本地的,也可以是在某些服务器上。根据文件的可用性,我必须更改图像(下载.png(可下载或不可用。

谁能帮忙?

我是JSP和servlet的新手,所以请详细说明解决方案。

确定资源是否可供下载的一种可能的解决方案是打开与该资源的连接并检查响应代码。响应可以告诉您连接是否成功。我们可以假设,如果连接成功,那么该文件可供下载。成功的连接将发送响应代码 200。我们可以假设任何其他响应代码都意味着连接不成功。

为此,我们可以创建一个名为 CheckResponseStatus 的 servlet,如下所示:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {             
    String remoteImageUrl = request.getParameter("remoteImageUrl");         
    String imageUrl = "http://localhost:8000/WEBAPP/images/download.png";
    URL url = new URL(remoteImageUrl);
    HttpURLConnection http = (HttpURLConnection)url.openConnection();
    int statusCode = http.getResponseCode();
    if (statusCode != 200) {
        imageUrl = "http://localhost:8000/WEBAPP/images/notAvailable.png";       
    }
    response.getWriter().write(imageUrl);        
}

我们将资源的 URL 作为查询字符串参数传递,并使用 request.getParameter("remoteImageUrl") 检索它。然后,我们打开与资源url.openConnection()的连接,并检索响应代码http.getResponseCode()

现在我们有了响应代码,我们对其进行测试以确定是否已成功连接到资源if (statusCode != 200) .如果是这样,我们将返回下载图像的 URL,否则返回不可用图像的 URL。

因此,如果资源可用,则此 servlet 将返回 http://localhost:8000/WEBAPP/images/download.png ,如果不可用,则返回 http://localhost:8000/WEBAPP/images/notavailable.png ,作为我们可以插入到 <img src=""> 标签中的文本字符串。

在 JSP 中,我们需要将资源的 URL 传递给 servlet。

 <%
     pageContext.setAttribute("FilePath1", "http://www.google.com/humans.txt");
     pageContext.setAttribute("FilePath2", "http://www.example.com/filedoesnotexist.doc");
 %>
 <a href="${FilePath1}">
      <img src="<jsp:include page="CheckResponseStatus?remoteImageUrl=${FilePath1}"/>"/>
 </a>
 <a href="${FilePath2}">
      <img src="<jsp:include page="CheckResponseStatus?remoteImageUrl=${FilePath2}"/>"/>
 </a>

在此示例中,我对 URL 进行了硬编码,并将它们作为属性添加到 pageContext 中。我这样做是为了让我们可以使用表达式语言而不是脚本(不建议使用脚本(。

我使用标准操作<jsp:include>来调用servlet。此操作发出对 servlet 的调用,以及来自 servlet 的任何响应,它都包含在转换后的 JSP 页面中。资源的名称作为查询字符串参数附加到对 servlet ${FilePath1} 的调用。此查询字符串由 servlet 使用 request.getParameter("remoteImageUrl") 检索。

这行代码允许我们动态测试作为参数传递给 CheckResponseStatus servlet 的任何文件的连接状态。

这只是一个概念证明,可以大幅改进。我只包括了使其工作所需的最低限度。您将需要使其更加健壮,处理异常和其他响应代码。

我希望这可以帮助您解决问题。

最新更新