好日子,我從我的數據庫中檢索一個簡單的字節數組以供下載時遇到了很多困難。我很清楚如何做到這一點,並且據我所知,我所有的基地都被覆蓋了;但無法找到相對路徑中的文件。 DesignModel:ASP .NET(4.5)從數據庫困難中檢索MVC byte []文件
public class Message
{
[Key]
public int Id { get; set; }
//...
public byte[] Attachment { get; set; }
public string ContentType { get; set; }
public string ContentName { get; set; }
}
的數據和元數據保存完美的罰款,所以我知道創作不是一個問題,這僅僅是我的檢索有問題。
視圖模型:
public class MessageAdd
{
//..
public HttpPostedFileBase Attachments { get; set; }
}
public class MessageBase : MessageAdd
{
public MessageBase()
{
url = HttpContext.Current.Request.Url.GetLeftPart(System.UriPartial.Authority);
}
public int Id { get; set; }
public string ContentType { get; set; }
public string ContentName { get; set; }
public byte[] Attachment { get; set; }
private string url = "";
public string AttachUrl
{
get
{
return string.Format("{0}/image/Message/Attachment{1}", url, Id);
}
}
}
消息控制器:
private Manager m = new Manager();
// GET: Message
[Authorize]
public ActionResult Inbox()
{
return View(m.Inbox());
}
經理級收件箱中的樂趣:
public IEnumerable<MessageBase> Inbox()
{
var messages = ds.Messages.Where(x => x.Recipient == uNm);
return (messages == null) ? null : Mapper.Map<IEnumerable<MessageBase>>(messages);
}
文件控制器:
private Manager m = new Manager();
[Route("image/Message/Attachment/{id}")]
public ActionResult GetMessageLogoById(int? id)
{
// Determine whether we can continue
if (!id.HasValue) { return HttpNotFound(); }
// Fetch the object, so that we can inspect its value
var fetchedObject = m.GetMessageById(id.Value);
if (fetchedObject == null)
{
return HttpNotFound();
}
else
{
// Return a file content result
// Set the Content-Type header, and return the photo bytes
return File(fetchedObject.Attachment, fetchedObject.ContentType, fetchedObject.ContentName);
}
GetMe ssageByID(在經理):
public MessageBase GetMessageById(int id)
{
var fetchedObject = Mapper.Map<MessageBase>(ds.Messages.Find(id));
return (fetchedObject == null) ? null
: fetchedObject;
}
的觀點:
//..
<th>
Attachment
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
//..
@{
if (item.ContentType != null)
{
if (item.ContentType.Contains("audio"))
{
<td>
<audio controls>
<source src="@item.AttachUrl" type="@item.ContentType">
Audio playback not supported.
</audio> <br />
<a href='@item.AttachUrl' download> Download audio</a>
</td>
}
else if (item.ContentType.Contains("video"))
{
<td>
<video width="300" height="280" controls>
<source src="@item.AttachUrl" type="@item.ContentType">
Video playback not supported.
</video> <br />
<a href='@item.AttachUrl' download> Download video</a>
</td>
}
else if (item.ContentType.Contains("image"))
{
<td>
<a href='@item.AttachUrl' download>
<img src='@item.AttachUrl' alt="@item.ContentName" title="@item.ContentType" style="width: 100px;" />
</a>
</td>
}
else
{
<td>
<a href='@item.AttachUrl' download>File - @item.ContentType</a>
</td>
}
}
else
{
<td>No Attachment.</td>
}
}
//..
}@
我已經用這種方法的另一個項目實際達到的結果,當我比較兩個我看不到我的邏輯有什麼區別。任何燈光棚將不勝感激。歡呼聲
請閱讀如何創建[mcve]。這是很多要求人們通讀的代碼... –