我想在asp.net mvc 5中显示所有图像(位于"~/files/ "
文件夹中)。就像那样:
public ActionResult uploadPartial()
{
var appData = Server.MapPath("~/files");
var images = Directory.GetFiles(appData).Select(x => new imagesviewmodel
{
Url = Url.Content("/files/" + Path.GetFileName(x))
});
return View(images);
}
并在视野中
@model IEnumerable<ckeditortest.Models.imagesviewmodel>
@foreach (var image in Model)
{
<a href="#" class="returnImage" data-url="@Request.Url.GetLeftPart(UriPartial.Authority)@image.Url">
<img src="@image.Url" alt="Hejsan" id="#image" data-source="@image.Url" width="200" height="200"/>
</a>
}
但是在asp.net核心我不知道我该怎么做
答案 0 :(得分:0)
你想要Directory.EnumerateFiles
。有关示例,请参阅this answer。您还必须替换Server.MapPath
,因为它在.NET Core中不可用。您可以使用this code执行此操作(注入IHostingEnvironment
并从中获取WebRootPath
)。
使用上述两种方法,您将获得此代码(未经测试):
public class MyController : Controller
{
private IHostingEnvironment _env;
public HomeController(IHostingEnvironment env)
{
_env = env;
}
public IActionResult Index()
{
var webRoot = _env.WebRootPath;
var appData = System.IO.Path.Combine(webRoot, "files");
var models = Directory.EnumerateFiles(appData).Select(x => new imagesviewmodel
{
Url = Url.Content(x)
});
return View(models);
}
}
您可以将此GetLeftPart
替换为this answer):
Request.Url.GetComponents(UriComponents.Scheme | UriComponents.StrongAuthority, UriFormat.Unescaped)