set src property in view to a url outside of the MVC3 project

前端 未结 2 1685
囚心锁ツ
囚心锁ツ 2021-02-14 12:06

I am trying to create an application that will display images that are stored locally on the webserver. Here is what I have in my view, note that \"entry\" are absolute addresse

相关标签:
2条回答
  • 2021-02-14 12:43

    The above code was useful for me, with a change like this

     System.Web.UI.Page page = new System.Web.UI.Page();
     string filePath = page.Server.MapPath("~/Log/" + fileName);
    
            if (!filePath.StartsWith(filePath))
    
            {
    
                throw new HttpException(403, "Forbidden");
            }
    
            return File(filePath, "Content-Disposition", "attachment;filename=TableImportLog.csv");
    

    }

    the file thrown to the user is with file name like this "attachment;filename=TableImportLog.csv", but i want the file name as "TableErrorLog.csv" need help for the same!

    0 讨论(0)
  • 2021-02-14 12:44

    You cannot directly serve images outside of your ASP.NET MVC 3 application to the client. That would be a huge security vulnerability if the client could access arbitrary files on your server.

    You will need to write a controller action that will return them and then point your src property of your <img> tags to this controller action.

    public class ImagesController: Controller
    {
        public ActionResult SomeImage()
        {
            return File(@"C:\Images\foo.jpg", "image/jpeg");
        }
    }
    

    and inside your view:

    <img src="@Url.Action("SomeImage", "Images")" alt="" />
    

    You could also pass the image name as parameter to the controller action:

    public class ImagesController: Controller
    {
        public ActionResult SomeImage(string imageName)
        {
            var root = @"C:\Images\";
            var path = Path.Combine(root, imageName);
            path = Path.GetFullPath(path);
            if (!path.StartsWith(root))
            {
                // Ensure that we are serving file only inside the root folder
                // and block requests outside like "../web.config"
                throw new HttpException(403, "Forbidden");
            }
    
            return File(path, "image/jpeg");
        }
    }
    

    and in your view:

    <img src="@Url.Action("SomeImage", "Images", new { image = "foo.jpg" })" alt="" />
    
    0 讨论(0)
提交回复
热议问题