Rem
Rem

Reputation: 105

How to serve a file from an ASP.NET Controller?

I want to do this with c# asp.net, can you tell me the actual methods I need to use to handle this part: {get file from filesystem}?

ActionResult FunctionToServeFile(fileName, guid)
{
    File result;
    var itemEntry = db.items.firstOrDefault(x => x.guid == guid);
    var itemPermissionsEntry = itemEntry.userPermissions
                              .firstOrDefault(x => x.user == user.identity.name);

    if(itemPermissionsEntry.view == true || itemPermissionsEntry.Modify == true)
    {
        result = {get file from filesystem}
        return result;
    }
    else
    {
        return error;
    }
}

Upvotes: 0

Views: 2021

Answers (3)

Rem
Rem

Reputation: 105

This is the solution I arrived at:

public ActionResult DownloadFile(string fileName, Guid guid)
        {
            Item item = db.Items.FirstOrDefault(x => x.ItemGUID == guid);

            if (item == null)
                return null;

            List <SecurityMask> accessList = GetAccessRightsForItem(item.item_id,
                                                ActiveDirectory.GetUserSID(User.Identity.Name));

            bool hasAccess = false || (accessList.Contains(SecurityMask.View) || accessList.Contains(SecurityMask.Modify));

            string filePath = Path.GetFullPath(Path.Combine(HttpRuntime.AppDomainAppPath,
                                        "Files\\Items", guid.ToString(), fileName));

            string mimeType = MimeMapping.GetMimeMapping(filePath);

            bool fileExists = System.IO.File.Exists(filePath);

            if (hasAccess && fileExists)
            {
                return File(System.IO.File.ReadAllBytes(filePath), mimeType);
            }
            return null;
        }

Upvotes: 2

Fourat
Fourat

Reputation: 2447

You have to have the file somewhere in your server, so just make a method to get that path and serve it through the controller like this :

string thefile = SomeModelClass.SomeMethod(fileName, guid); // get full path to the file
var cd = new System.Net.Mime.ContentDisposition
{
    FileName = Path.GetFileName(thefile),
    Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
string fileext = Path.GetExtension(thefile);
string mimeType = SomeMetodToMapextensionToMimeType(fileext); // You have to implement this by yourself
return File(System.IO.File.ReadAllBytes(thefile), mime);

Upvotes: 1

Richard
Richard

Reputation: 109005

There is direct support for this with FileResult, and Controller has a set of helpers:

In your action:

return File(filename, contentType);

Upvotes: 4

Related Questions