I can upload and download the uploaded files, but I want that users to be able to see only their files. (user1 to see only his data, not also user2's data) How could I do it? Any idea could help. Thanks!
This is my controller, I know that between admin, user, editor I can restrict the access with Authorize, but this wouldn't help me restricting the access between user_id's.
(need to mention that privacy is a very important aspect of my project)
public class FileUploadController : Controller
{
// GET: FileUpload
public ActionResult Index()
{
var items = GetFiles();
return View(items);
}
// POST: FileUpload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if(file != null && file.ContentLength > 0 )
try
{
string path = Path.Combine(Server.MapPath("~/Files"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch(Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "You have not specified a file.";
}
var items = GetFiles();
return View(items);
}
public FileResult Download(string downloadedfile)
{
var FileVirtualPath = "~/Files/" + downloadedfile;
return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
}
private List <string> GetFiles()
{
var dir = new System.IO.DirectoryInfo(Server.MapPath("~/Files"));
System.IO.FileInfo[] fileNames = dir.GetFiles("*.*");
List<string> items = new List<string>();
foreach (var file in fileNames)
{
items.Add(file.Name);
}
return items;
}
}
This is the view:
<h2> File Upload </h2>
@model List<string>
@using (Html.BeginForm("Index", "FileUpload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file"> Upload </label>
<input type="file" name="file" id="file" />
<br /><br />
<input type="submit" value="Upload" />
<br /><br />
@ViewBag.Message
<br/>
<h2>Documents list</h2>
<table style="width:100%">
<tr>
<th> File Name </th>
<th> Link </th>
</tr>
@for (var i = 0; i <= (Model.Count)-1 ; i++)
{
<tr>
<td>@Model[i].ToString() </td>
<td>@Html.ActionLink("Download", "Download", new { downloadedfile = Model[i].ToString() }) </td>
</tr>
}
</table>
}
<style>
table, th, td {
border: 1px solid white;
}
</style>
You can separate to folder, create a folder with the id of the user, and put the data in user folder.
When you gonna list, only show the folder of the user