如果我有下面的情况,那我就成功了。处理图像上传和存储在db中。记住这些代码将如何实现多个图像上传。 谢谢。
首先是第一件事。
PropertyViewModel.cs
...
public byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
public PropertyViewModel(Property x)
{
....
ImageData = x.ImageData;
ImageMimeType = x.ImageMimeType;
}
public void ToDomainModel(Property x)
{
....
x.ImageData = ImageData;
x.ImageMimeType = ImageMimeType;
}
现在形成Create.cshtml razor页面
@using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
<input type="file" name="Image"/>
}
}
处理请求的控制器
[HttpPost]
public ActionResult Create(PropertyViewModel newProperty, HttpPostedFileBase image)
{
if (ModelState.IsValid)
{
if (image != null)
{
newProperty.ImageMimeType = image.ContentType;
newProperty.ImageData = new byte[image.ContentLength];
image.InputStream.Read(newProperty.ImageData, 0, image.ContentLength);
}
using (session...)
{
using (...begin transaction)
{
MyDomain.Property model = new MyDomain.Property();
newProperty.ToDomainModel(model);
..session save model
.. commiting session
}
}
return RedirectToAction("Index");
}
else
{
return View(newProperty);
}
}
答案 0 :(得分:0)
@using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
<input type="file" name="Image"/>
<input type="file" name="Image"/>
<input type="file" name="Image"/>
<input type="file" name="Image"/>
}
或者如果浏览器支持HTML5,您可以在上传对话框中选择多个文件:
@using (Html.BeginForm("Create", "Property", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
<input type="file" name="Image" multiple="multiple"/>
}
然后:
public ActionResult Create(PropertyViewModel newProperty, IEnumerable<HttpPostedFileBase> image)