[英]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.