我是一名学生开发人员在.Net MVC5,我想插入图像从新用户到我的数据库。我发现了很多用于byte[]数据类型的方法,但根据我的研究,没有用于字符串数据类型的来源。(例如:Entity Framework 5 Code first adding an image)。如何处理我的数据库中ImageUrl的字符串列?你能在这个问题上帮我吗?
我的模型:
public class usersModel{
public string userImageUrl{get;set;}
}
我的控制器:
public class UsersController : Controller
{
AgmEntities db = new AgmEntities();
public ActionResult Create()
{
return View("Create", new usersModel());
}
[HttpPost]
public ActionResult Create(usersModel uModel,HttpPostedFileBase file)
{
if (!ModelState.IsValid)
{
return View("Create");
}
var user = new Users();
if(file !=null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string imgPath = Path.Combine(Server.MapPath("~/User_Images/"), fileName);
file.SaveAs(imgPath);
}
user.userImageUrl = "~/User_Images/" + file.FileName;/*Error line*/
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
}
我的cshtml:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-group">
@Html.LabelFor(model => model.userImageUrl, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="ImageFile" />
@Html.ValidationMessageFor(model => model.userImageUrl, "", new { @class = "text-danger" })
</div>
</div>
}
发布于 2019-04-17 08:31:48
必须在表单中添加新的{ enctype="multipart/form-data"}
才能允许上载文件。
Html.BeginForm(
null, null, FormMethod.Post, new { enctype="multipart/form-data"})
将cshtml代码更改为:
@using (Html.BeginForm(
null, null, FormMethod.Post, new { enctype="multipart/form-data"}))
{
@Html.AntiForgeryToken()
<div class="form-group">
@Html.LabelFor(model => model.userImageUrl, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="ImageFile" />
@Html.ValidationMessageFor(model => model.userImageUrl, "", new { @class = "text-danger" })
</div>
</div>
}
并在if user.userImageUrl = "~/User_Images/" + file.FileName;/*Error line*/
中移动这行代码,在本例中,file.FileName
可能为空。
if(file !=null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string imgPath = Path.Combine(Server.MapPath("~/User_Images/"), fileName);
file.SaveAs(imgPath);
user.userImageUrl = "~/User_Images/" + file.FileName;/*Error line*/
}
还有一点需要注意的是,与name of input
类型的文件一样,需要更改parameter name
:
<input type="file" name="ImageFile" /> to <input type="file" name="file" />
https://stackoverflow.com/questions/55717291
复制相似问题