asp net在View视图下通过javascript访问服务器上的文件

采用javascript访问服务器上的文件,文件存在则打开文件,不存在返回不存在

控制器:

[HttpPost]
public ActionResult CheckFileExists(string aFile)
{
  // 检查文件是否存在

  string filePath = Server.MapPath("~" + aFile);//返回与Web服务器上的指定虚拟路径相对应的物理文件路径

  if (System.IO.File.Exists(filePath)) //theFile包括完整的路径和文件
  {
  return Content("文件存在");
  }
  else
  {
  return Content("文件尚未发布");
  }

}

 view前端:

 <script>

function GetFile(s) {

//s是科室
if (s == '')
  theFile = "/报告/" + document.getElementById("currPeriod").value + "/" + "全院报告.pdf"
else
  //科室报告
  theFile = "/报告/" + document.getElementById("currPeriod").value + "/" + s + ".pdf";

 $(document).ready(function () {

  $.ajax({
  url: '/FeeJiXiao/CheckFileExists',
  type: 'POST',
  data: { aFile: theFile },
  success: function (data) {
    if (data == '文件存在' )
    {
      window.top.location.href = theFile;//无法 _blank
      window.open(theFile, '_blank');//打开文件
       } else
      alert(data); // 弹出包含服务器返回的字符串的警告框

    },
    error: function (error) {
    console.log('Error:', error);
  }
  });
  });

}

</script>

视图动态调用javascript函数

<td>
  <a href="javascript:;" onclick="GetFile('@item.FeeDeptName');"
</td>

 

posted @ 2024-03-26 12:23  Biyuanguang  阅读(1)  评论(0编辑  收藏  举报