2017-07-20 60 views
0

我想用c#asp.net來做到這一點,你能告訴我我需要用來處理這部分的實際方法:{從文件系統獲取文件}?如何從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; 
    } 
} 

回答

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

沒有與FileResult這種直接的支持,並Controller有一組助手:

在你的行動:

return File(filename, contentType); 
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; 
     } 
相關問題