【问题标题】:Opening a file from spring URL Tag从 spring URL 标签打开文件
【发布时间】:2017-01-31 05:49:00
【问题描述】:

我四处寻找解决方案,但找不到任何解决方案。

我将一个文件存储在我的本地驱动器中,并将该文件的路径存储在我的 mongoDB 中, 检索路径后,我想为 URL 提供来自 DB 的路径。当我单击该 URL 时,该路径应打开该相关文件。
我的代码是

数据库中的数据为:

"filePath" : "C:/myfiles/Resume_Vipul.docx"

在前端访问它:

<c:forEach var="ser" items="${services}" varStatus="status">
<td class="text-center"><a href='<spring:url value="${ser.filePath}" />'>file</a></td>
</c:forEach>

当我点击 URL 时,它给我的错误是:

Not allowed to load local resource: file:///C:/myfiles/Resume_Vipul.docx

执行此操作的正确方法是什么。 任何帮助将不胜感激。

【问题讨论】:

  • 在您的web.xml 中的目录中添加一个servlet 映射,并使用映射别名代替您的${ser.filePath}"

标签: javascript jquery spring-mvc jstl


【解决方案1】:

您应该以文件名作为参数向控制器发送请求,并将字节作为响应发送回,像这样,

ServletContext cntx= req.getServletContext();
  // Get the absolute path of the image
  String filename = cntx.getRealPath("Images/button.png");
  // retrieve mimeType dynamically
  String mime = cntx.getMimeType(filename);
  if (mime == null) {
    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return;
  }

  resp.setContentType(mime);
  File file = new File(filename);
  resp.setContentLength((int)file.length());

  FileInputStream in = new FileInputStream(file);
  OutputStream out = resp.getOutputStream();

  // Copy the contents of the file to the output stream
   byte[] buf = new byte[1024];
   int count = 0;
   while ((count = in.read(buf)) >= 0) {
     out.write(buf, 0, count);
  }
out.close();
in.close();

我认为从客户端访问本地资源不是一个好主意。考虑为此向服务器发出单独的请求。在您的情况下,您可以将资源路径作为String 参数发送到服务器。

【讨论】:

  • 我会尝试实现这个
猜你喜欢
  • 1970-01-01
  • 2015-02-09
  • 2020-08-11
  • 2012-05-22
  • 2015-07-22
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 1970-01-01
相关资源
最近更新 更多