[英]ASP.NET MVC upload image
我已經找到一些執行此操作的代碼,並嘗試將其實現到我的項目中,但是到目前為止,該操作沒有成功。 我沒有收到任何錯誤,但是我沒有看到任何圖像存儲在Visual Studio的圖像目錄中。
視圖:
@using (Html.BeginForm())
{
<span>Please enter your story here:</span>
<textarea id="testimonial" name="testimonial"></textarea>
<button type="submit">Submit</button>
<input type="file" name="file" />
}
控制器:
[HttpPost]
public ActionResult Create(Testimonials testimonials)
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
}
TestimonialsContext testContext = new TestimonialsContext();
testContext.testimonialContext.Add(testimonials);
testContext.SaveChanges();
return RedirectToAction("Index");
}
if塊下面的部分工作正常。 這只是將文本區域的內容保存到數據庫中。 有什么想法嗎? 我需要對模型進行任何更改嗎?
模型:
[Table("Testimonials")]
public class Testimonials
{
public int Id { get; set; }
public string Testimonial { get; set; }
}
上下文類:
public class TestimonialsContext:DbContext
{
public DbSet<Testimonials> testimonialContext { get; set; }
}
您的文件未發布,因為您在表單上沒有必需的enctype
屬性。 更改視圖以使用
@using (Html.BeginForm("Create", "Testimonials", FormMethod.Post, new { enctype = "multipart/form-data" }))
現在,您將獲取並保存文件,但是與您的“ Testimonials
對象沒有任何關系,因此無法檢索它。 您將需要在“個人Testimonials
表中添加其他字段以存儲文件屬性(如果“個人Testimonials
可以包含多個圖像,則需要單獨的表)。 我還建議您使用唯一的標識符將文件保存到服務器(例如,如果兩個用戶上傳的文件具有相同的名稱,則可以防止意外覆蓋的Guid
)。 您修改的模型可能是
public class Testimonials
{
public int Id { get; set; }
public string Testimonial { get; set; }
public string ImagePath { get; set; }
public string ImageDisplayName { get; set; }
}
我還建議為包含上述屬性以及public HttpPostedFileBase Image { get; set; }
的視圖使用視圖模型public HttpPostedFileBase Image { get; set; }
public HttpPostedFileBase Image { get; set; }
public HttpPostedFileBase Image { get; set; }
以便您可以牢固地綁定到模型並添加驗證屬性(例如,假設您不想允許用戶上傳2GB文件,則為[FileSize]
屬性)。 您的控制器方法將是
[HttpPost]
public ActionResult Create(TestimonialVM model)
{
// ModelState.IsValid check omitted
Testimonials testimonials = new Testimonials();
// map view model properties to the data model
....
if (model.Image != null && model.Image.ContentLength > 0)
{
string displayName = model.Image.FileName;
string fileExtension = Path.GetExtension(displayName);
string fileName = string.Format("{0}.{1}", Guid.NewGuid(), fileExtension)
string path = Path.Combine(Server.MapPath("~/Images/"), fileName)
model.Image.SaveAs(path);
// Update data model
testimonials.ImagePath = path;
testimonials.ImageDisplayName = displayName;
}
TestimonialsContext testContext = new TestimonialsContext();
testContext.testimonialContext.Add(testimonials);
testContext.SaveChanges();
return RedirectToAction("Index");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.