我有一个收集员工详细信息的项目,因为我必须通过网址路径添加员工图片或浏览照片并将此链接保存到表格中。如何做到这一点?
模型类
public partial class Board
{
public int Id { get; set; }
public string Name { get; set; }
public string Designation { get; set; }
public string Phone { get; set; }
public string PhotoUrl { get; set; }
}
控制器
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection fc, HttpPostedFileBase file)
{
Board tbl = new Board();
var allowedExtensions = new[] { ".Jpg", ".png", ".jpg", "jpeg" };
//tbl.Id = fc["Id"].ToString();
tbl.PhotoUrl = file.ToString(); //getting complete url
tbl.Name = fc["Name"].ToString();
tbl.Designation = fc["Designation"].ToString();
tbl.Phone = fc["Phone"].ToString();
var fileName = Path.GetFileName(file.FileName); //getting only file name(ex-ganesh.jpg)
var ext = Path.GetExtension(file.FileName); //getting the extension(ex-.jpg)
if (allowedExtensions.Contains(ext)) //check what type of extension
{
string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension
string myfile = name + "_" + tbl.Id + ext; //appending the name with id
// store the file inside ~/project folder(Img)
var path = Path.Combine(Server.MapPath("~/Img"), myfile);
tbl.PhotoUrl = path;
db.Boards.Add(tbl);
db.SaveChanges();
file.SaveAs(path);
}
else
{
ViewBag.message = "Please choose only Image file";
}
return View();
}
视图
@using(Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<img id="user_img" height="100" width="90" style="border:solid" />
</div>
<div>
<input type="file" title="search image" id="file" name="file" onchange="show(this)" />
</div>
<div>UserId</div>
<div>
<input type="text" id="txt_id" name="id" />
</div>
<div>UserName</div>
<div>
<input type="text" id="txt_name" name="Name" />
</div>
<div>
<input type="submit" title="save" />
</div>
}
如何通过浏览路径添加图像并将图片作为路径保存到表格,并将图像副本保存到asp.net mvc中特定项目中的文件夹。当我编写显示错误的代码时
对象引用未设置为对象的实例
为什么会出现这个错误?