从HttpHostedFileBase检查FileName是文件名或文件路径

时间:2014-06-09 05:44:49

标签: c# asp.net-mvc file-upload asp.net-mvc-5 kendo-upload

我正在开发一个在数据库中存储文件名的应用程序。对于Mozilla& Chrome它只显示FileName,但在IE中显示文件的完整路径。现在我想检查给定的文件名是文件名还是文件路径。有没有办法做到这一点?

这是我的代码:

public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
{
  byte[] image = null;
  var file = attachments.First();
  // Some browsers send file names with full path. We only care about the file name.
  string filePath = Server.MapPath(General.FaxFolder + "/" + file.FileName);
  file.SaveAs(filePath);
  FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  using (BinaryReader br = new BinaryReader(fs))
  {
    image = br.ReadBytes((int)fs.Length);
  }
  TempData["Image"] = image;
  System.IO.File.Delete(filePath);            
  return Json(new { status = "OK", imageString = Convert.ToBase64String(image) }, "text/plain");
}

2 个答案:

答案 0 :(得分:6)

好吧,如果你只在任何浏览器中获取文件名,那么你应该写

Path.GetFileName(e.fileName);

它只会在任何浏览器中返回文件名 感谢

答案 1 :(得分:2)

您可以做的只是使用,而不是检查文件是否有路径 GetFileName(path);方法