简体   繁体   中英

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;
    }
}

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

In your action:

return File(filename, contentType);

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);

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;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM