下载如何以我们上传的形式执行功能
存储二进制格式如何从二进制文件中检索数据
控制器动作
你的意思是要将文件上传到数据库,然后从数据库中下载指定的文件?
如您所说,要将文件上传到数据库中,您需要使用 IFormFile。像这样的代码:
public class Product
{
[Key]
public int ProId { get; set; }
public string ProName { get; set; }
public string ProImageName { get; set; }
public byte[] ProImageContent { get; set; }
public string ProImageContentType { get; set; }
//you can add another properties
}
上传方式:
[HttpPost]
public async Task<IActionResult> CreateAsync(ProductViewModel product)
{
if (ModelState.IsValid)
{
//save image to database.
using (var memoryStream = new MemoryStream())
{
await product.FormFile.CopyToAsync(memoryStream);
// Upload the file if less than 2 MB
if (memoryStream.Length < 2097152)
{
//Convert the View
var file = new Product()
{
ProImageName = product.FormFile.FileName,
ProImageContent = memoryStream.ToArray(),
ProImageContentType = product.FormFile.ContentType,
ProName = product.Name
};
_dbcontext.Products.Add(file);
await _dbcontext.SaveChangesAsync();
}
else
{
ModelState.AddModelError("File", "The file is too large.");
}
}
return RedirectToAction(nameof(Index));
}
return View();
}
然后,要下载文件,在索引列表中,您可以添加带有主键的超链接,如下所示:
@Html.ActionLink("DownLoad Image", "DownloadImage", new { id=item.ProId })
整个索引页代码:
@model List<MVC6App.Data.Product>
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
ProId
</th>
<th>
ProName
</th>
<th>
ProImageName
</th>
<th></th>
</tr>
</thead>
<tbody>
@if (Model != null && Model.Count > 0)
{
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.ProId)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProName)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProImageName)
</td>
<td>
@Html.ActionLink("DownLoad Image", "DownloadImage", new { id=item.ProId })
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
}
else
{
<tr><td colspan="4"> empty</td></tr>
}
</tbody>
</table>
控制器索引操作:
public IActionResult Index()
{
var result = _dbcontext.Products.ToList();
return View(result);
}
然后,在 DownLoadImage 动作方法中,根据主键查询数据库并获取图像/文件内容,然后返回 File 结果以下载文件:
public IActionResult DownloadImage(int id)
{
byte[] bytes;
string fileName, contentType;
var item = _dbcontext.Products.FirstOrDefault(c => c.ProId == id);
if(item != null)
{
fileName = item.ProImageName;
contentType = item.ProImageContentType;
bytes = item.ProImageContent;
return File(bytes, contentType, fileName);
}
return Ok("Can't find the Image");
}
结果是这样的: