Reputation: 446
I have files saved in a Project Folder
D:\Maarjaa\Marjaa\Content\Uploads
Now I want to Display name of these files( not the full URL)
as
lakes of kaghan.jpg
lakes of gilgit.jpg
not as
D:\Maarjaa\Marjaa\Content\Uploads\lakes of kaghan.jpg
Additionally I want to give download links to thes files, so that a user can download these files
Upvotes: 2
Views: 5199
Reputation: 446
I did it, In my View
<ul>
@foreach(var Item in(IEnumerable<Marjaa.Data.MultimediaFile>) ViewData["Files"])
{
<li><a href=" @Url.Content("~/Content/Uploads/" + System.IO.Path.GetFileName(Item.MultimediaFileUrl))">@System.IO.Path.GetFileName(Item.MultimediaFileUrl)</a> </li>
}
</ul>
From my Controller Just Sent a list to View
IList<MultimediaFile> list = d.MultimediaFiles.Where(l => l.MultmediaId == id).ToList();
ViewData["Files"] = list;
Upvotes: 4
Reputation: 7605
Many different ways to do this. Here's one:
Create a class for your files
public class Image
{
public string Name { get; set; }
public string Path { get; set; }
}
and a view model class
public class ViewModel
{
public List<Image> Images { get; set; }
public string Path { get; set; }
}
Then in your controller, populate the view model and the name and path properties for each Image object in the list. You'll need to import the System.IO namespace.
public ActionResult DisplayFilesForDownload( )
{
var viewModel = new ViewModel
{
Path = @"D:\Maarjaa\Marjaa\Content\Uploads",
Images = new List<Image>()
};
var paths = Directory.GetFiles(viewModel.Path).ToList();
foreach (var path in paths)
{
var fileInfo = new FileInfo( path );
var image = new Image
{
Path = path, Name = fileInfo.Name
};
viewModel.Images.Add(image);
}
return View( viewModel);
}
And the method to allow downloads. I am assuming all your files are images. If not, just adjust the MediaTypeName as needed.
public FileResult Download(string filePath, string fileName)
{
var file = File(filePath, System.Net.Mime.MediaTypeNames.Image.Jpeg, fileName);
return file;
}
and finally the view. Image.Name is used to display the shortened file name and Image.Path is used to tell the download method where to fetch the file from.
@model FullyQualified.Path.ToYour.ViewModel
@foreach (var image in Model.Images)
{
<p>@Html.ActionLink(image.Name, "Download", "ControllerName", new{filePath = image.Path, fileName = image.Name}, null)</p>
}
Hope this helps get you on your way.
Upvotes: 4