Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从spring URL标记打开文件_Javascript_Jquery_Spring Mvc_Jstl - Fatal编程技术网

Javascript 从spring URL标记打开文件

Javascript 从spring URL标记打开文件,javascript,jquery,spring-mvc,jstl,Javascript,Jquery,Spring Mvc,Jstl,我四处寻找解决办法,但找不到任何解决办法 我正在本地驱动器中存储一个文件,并在mongoDB中存储该文件的路径, 在检索路径之后,我想给URL一个来自DB的路径。当我单击该URL时,该路径应打开该相关文件。 我的代码如下 数据库中的数据为: "filePath" : "C:/myfiles/Resume_Vipul.docx" 通过以下方式在前端访问它: <c:forEach var="ser" items="${services}" varStatus="status"> <

我四处寻找解决办法,但找不到任何解决办法

我正在本地驱动器中存储一个文件,并在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>
执行此操作的正确方法是什么。
任何帮助都将不胜感激。

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

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
参数发送到服务器。

web.xml
中添加一个servlet映射到您的目录,并在
${ser.filePath}中使用映射别名。
我将尝试实现这一点
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();