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

时间:2017-07-20 07:45:27

标签: c# asp.net asp.net-mvc

我想用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;
    }
}

3 个答案:

答案 0 :(得分:4)

FileResult有直接支持,Controller有一组帮助:

在你的行动中:

return File(filename, contentType);

答案 1 :(得分:1)

你必须在服务器的某个地方放置文件,所以只需创建一个方法来获取该路径并通过控制器提供它,如下所示:

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

答案 2 :(得分:0)

这是我到达的解决方案:

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