How to view a file after uploading it to App_Data / Uploads in MVC 3 using Razor?

I am new to mvc and I have a problem. I was looking for an answer, and I could not find it, but I am very sure that something missed me. The problem is that I do not know how to get the file after uploading to the App_Data folder. I use the same code as in all forums:

For my viewing, I use this

@using (Html.BeginForm("Index", "Home", FormMethod.Post, 
new { enctype="multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="submit" />
}

For my controller, I use this

public class HomeController : Controller
{
// This action renders the form
public ActionResult Index()
{
    return View();
}

// This action handles the form POST and the upload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    // Verify that the user selected a file
    if (file != null && file.ContentLength > 0) 
    {
        // extract only the fielname
        var fileName = Path.GetFileName(file.FileName);
        // store the file inside ~/App_Data/uploads folder
        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
        file.SaveAs(path);
    }
    // redirect back to the index action to show the form once again
    return RedirectToAction("Index");        
  }
} 

My model

public class FileDescription
{
    public int FileDescriptionId { get; set; }
    public string Name { get; set; }
    public string WebPath { get; set; }
    public long Size { get; set; }
    public DateTime DateCreated { get; set; }
}

I want to upload a file to the database, and then WebPath - a link to my file. I hope I made myself clear enough. Any help would be really appreciated. Thanks

+5
source share
3 answers

( ASP.NET) - Server.MapPath("~/App_Data/uploads/<yourFileName>"), (, C:/inetpub/wwwroot/MyApp/Add_Data/MyFile. TXT).

App_Data URL- . , , . , URL-, .

, , . ( , ), , .

+10

, - , PDF:

public ActionResult DownloadPDF(string fileName)
{
    string path = Server.MapPath(String.Format("~/App_Data/uploads/{0}",fileName));
    if (System.IO.File.Exists(path))
    {
        return File(path, "application/pdf");
    }
    return HttpNotFound();
}
+8

You must use a common handler to access files. IMO storing images / files in the App_Data folder is best practice since it does not serve files by default.

Of course, it depends on your needs. If you don't care who can access the images, just upload them to a folder outside the app_data folder :)

It all depends on your needs.

0
source

All Articles