[英]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;
}
}
您必須將文件放置在服務器中的某個位置,因此只需創建一個獲取該路徑並通過控制器將其提供服務的方法,如下所示:
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.