我從部分共享視圖中加載產品圖像,我試圖使用前一個問題中建議的Ifrom文件。嘗試使用asp.net核心上傳文件
所以在我的產品控制器,我有以下方法
編輯
我只想保存文件的路徑在數據庫中,然後保存在磁盤上的文件是什麼正確的方式來實現這一點。
public ActionResult FileUpload(ProductImages model)
{
if (model.Image != null)
{
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
var filePath = Path.Combine(uploads, GetUniqueName(model.Image.FileName));
model.Image.CopyTo(new FileStream(filePath, FileMode.Create));
}
// to do : Return something
return RedirectToAction("Index", "Home");
}
我的產品圖片類
public class ProductImages
{
[Key]
public int ProductImageId { get; set; }
public int ProductID { get; set; }
public string ProductImageTitle { get; set; }
public string ProductImageUploadUrl { get; set; }
public string ProductImageRealPath { get; set; }
public string ServerIpAddress { get; set; }
public string ProductImageAltTag { get; set; }
public int DisplayOrder { get; set; }
public IFormFile Image { set; get; }
}
我的共享佈局,我通過以下加載。
Product Images
@await Html.PartialAsync("_ProductPicture", Model)
</div>
這是我認爲我做錯了什麼與我已經宣佈了IFormFile
@model solitude.models.ProductImages
<div class="form-group">
<form asp-action="FileUpload" enctype="multipart/form-data">
<input asp-for="ImageCaption" />
<input asp-for="ImageDescription" />
<input asp-for="MyImage" />
<input type="submit" />
</form>
</div>
我收到以下錯誤
的方式爲我的共享視圖代碼AggregateException:發生一個或多個錯誤。 (屬性「ProductImages.Image」是一個接口類型(「IFormFile」)的,如果是 導航屬性通過將其流延到映射的實體類型手動配置此 屬性的關係,否則使用該忽略 屬性。 '[NotMapped]' 屬性或通過在 'OnModelCreating' 使用 'EntityTypeBuilder.Ignore') System.Threading.Tasks.Task.ThrowIfExceptional(布爾 includeTaskCanceledExceptions)
InvalidOperationException異常:屬性「ProductImages.Image '是一個 接口類型('IFormFile')。如果它是一個手動導航屬性 通過將其轉換爲映射的 實體類型來配置此屬性的關係,否則使用'[NotMapped]' 屬性或使用'OnModelCreating'中的'EntityTypeBuilder.Ignore'來忽略該屬性。
編輯2
[HttpPost] 公共的ActionResult文件上傳(ProductImageVm模型) { 如果(model.Image!= NULL){ 變種 上傳= Path.Combine(hostingEnvironment.WebRootPath ,「上傳」); var fileId = GetUniqueName(model.Image.FileName); VAR文件路徑= Path.Combine(上載,FILEID); model.Image.CopyTo(新的FileStream(文件路徑的FileMode。創建));
// to do : Save the record in ProductImage table
var pi = new ProductImages { ProductID = model.ProductId };
pi.ProductImageTitle = model.Title;
pi.ProductImageRealPath = fileId; //Storing the fileId
_context.ProductImages.Add(pi);
_context.SaveChanges();
}
return RedirectToAction("Index", "Home");
}
現在有一件事我加載另一個表單中的表單會這樣你不應該使用IFormFile
類型屬性在實體類的問題
首先,您希望將文件存儲在磁盤和數據庫中?對於數據庫,您應該在您的實體中使用字節數組作爲屬性類型。應該在你的視圖模型中使用IFormFile。 – Shyju
嗨@Shyju我只想將文件的路徑存儲在數據庫中,然後將文件存儲在磁盤上。抱歉應該更清楚。 – rogue39nin
@Shyju我重新調整了編輯的內容,所以我在這個問題上讓新人更清楚。 – rogue39nin