我的視圖中有一個帶有輸入元素的表單。
<input asp-for="Image" id="mainImageInput" type="file" onchange="readURL(this,'mainImage')" accept="image/jpeg, image/png" class="form-control"/>
我將所有影像作為位元組 [] 存盤在資料庫中。如何將 byte[] 轉換為 IFormFile 并將其發送到輸入元素中的視圖?不,我不是在問如何顯示影像,我想將它直接插入到輸入元素中,就好像用戶使用“瀏覽”選擇了它一樣。
我試著寫這個,但它不起作用:
var ad = _context.Advertisements
.Select(x => new {
Id = x.Id,
Title = x.Title,
Description = x.Description,
Price = x.Price,
Location = x.Location,
CategoryId = x.CategoryId,
ImageInBase64 = Convert.ToBase64String(x.Image),
UserId = x.UserId,
ImageInByteArray=x.Image
})
.FirstOrDefault(x=>x.Id==id);
IFormFile file = null;
using (var stream = new MemoryStream(ad.ImageInByteArray))
{
file = new FormFile(stream, 0, ad.ImageInByteArray.Length, "name", "fileName");
}
var viewModel = new AdvertisementViewModel()
{
Id = ad.Id,
Title = ad.Title,
Description = ad.Description,
Price = ad.Price,
Location = ad.Location,
CategoryId = ad.CategoryId,
ImageInBase64 = ad.ImageInBase64,
UserId = ad.UserId,
Image = file
};
return View("Edit",viewModel);
這是提交表單后我應該收到我的影像的操作,所有其他屬性都在那里,但我的影像為空。
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
public async Task<IActionResult> Edit(AdvertisementViewModel viewModel)
{
// viewmodel.Image is null, so my model state will always be invalid
// need a workaround
if (!ModelState.IsValid)
{
return View(viewModel);
}
}
uj5u.com熱心網友回復:
不,我不是在問如何顯示影像,我想將它直接插入到輸入元素中,就好像用戶使用“瀏覽”選擇了它一樣。
由于 Broswer 的安全原因,我認為我們不能將值設定為<input type='file' />.
相關帖子,希望對你有用:
1. 如何為 HTML 中的檔案輸入設定值?
2.為輸入檔案表單設定默認值[重復]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444893.html
標籤:C# 网 asp.net-mvc asp.net 核心 实体框架核心
