繁体   English   中英

如何从ASP.NET控制器提供文件?

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

我想使用c#asp.net做到这一点,您能告诉我处理这部分所需的实际方法吗:{从文件系统获取文件}?

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

FileResult直接对此提供FileResultController有一组帮助器:

在您的行动中:

return File(filename, contentType);

您必须将文件放置在服务器中的某个位置,因此只需创建一个获取该路径并通过控制器将其提供服务的方法,如下所示:

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

这是我到达的解决方案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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