想要将图像保存到文件夹并将url保存在数据库中
本文关键字:保存 存在 url 数据库 图像 文件夹 | 更新日期: 2023-09-27 18:09:42
我是asp.net mvc的新手。这里我有一个问题,在控制器图像上传任何人可以提供帮助吗??这个例子控制器是我从互联网上获取的,我应该怎么修改和编码viewnya,这里我想通过"AvatarUrl"保存图像
Model> EmployeeServices
public class EmployeeModel{
[ScaffoldColumn(false)]
public int EmployeeID { get; set; }
[Required(ErrorMessage = "Please Enter Position ID")]
public int PositionID { get; set; }
[Required(ErrorMessage = "Please Enter NO PEK")]
public string NoPEK { get; set; }
[Required(ErrorMessage = "Please Enter NO KTP")]
public string NoKTP { get; set; }
[Required(ErrorMessage = "Please Enter TaxID")]
public string TaxID { get; set; }
[Required(ErrorMessage = "Please Enter FirstName")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please Enter LastName")]
public string LastName { get; set; }
[Required(ErrorMessage = "Please Enter OrganizationID")]
public int OrganizationID { get; set; }
[Required(ErrorMessage = "Please Enter BirthPlace")]
public string BirthPlace { get; set; }
[Required(ErrorMessage = "Please Enter BirthDay")]
public System.DateTime BirthDay { get; set; }
[Required(ErrorMessage = "Please Enter Gender")]
public string Gender { get; set; }
[Required(ErrorMessage = "Please Enter Religion")]
public string Religion { get; set; }
[Required(ErrorMessage = "Please Enter TaxAddress")]
public string TaxAddress { get; set; }
[Required(ErrorMessage = "Please Enter Home Address")]
public string HomeAddress { get; set; }
[Required(ErrorMessage = "Please Enter Current Address")]
public string CurrentAddress { get; set; }
[Required(ErrorMessage = "Please Enter Phone Number")]
public string PhoneNumber { get; set; }
[Required(ErrorMessage = "Please Enter Email")]
public string Email { get; set; }
[Required(ErrorMessage = "Please Enter IsAuditor")]
public string IsAuditor { get; set; }
[Required(ErrorMessage = "Please Enter TaxProvince ")]
public int TaxProvinceID { get; set; }
[Required(ErrorMessage = "Please Enter Tax City ")]
public int TaxCityID { get; set; }
[Required(ErrorMessage = "Please Enter Home Province ")]
public int HomeProvinceID { get; set; }
[Required(ErrorMessage = "Please Enter Home City")]
public int HomeCityID { get; set; }
[Required(ErrorMessage = "Please Enter Current Province")]
public int CurrentProvinceID { get; set; }
[Required(ErrorMessage = "Please Enter Current City")]
public int CurrentCityID { get; set; }
[Required(ErrorMessage = "Please Enter Avatar Url")]
public string AvatarUrl { get; set; }
}
Controller> EmployeesController
[HttpPost]
public ActionResult Create(EventModel eventmodel, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
var filename = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), filename);
file.SaveAs(path);
tyre.Url = filename;
_db.EventModels.AddObject(eventmodel);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(eventmodel);
}
上传文件,存储在本地文件系统中,然后保存到数据库是一种常见的模式。这些是我的建议。
1。不要使用上传的文件名作为文件名
这很常见:
var filename = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), filename);
file.SaveAs(path);
别这么做。原因如下:
a)文件名可能冲突。b)远程文件名可能与本地文件系统不兼容。c)有人可能会尝试恶意文件名,这样做可能会破坏您的服务器。
相反,生成您自己的文件名(可能使用GUID, GUID.NewGuid().ToString()
)并将原始文件名存储在数据库中。
2。不要将所有文件存储在一个文件夹
在某些时候,你的文件夹会包含太多的文件,操作系统无法快速处理。
按一些有用的东西对文件进行分区,比如用户ID。这也有助于隔离用户之间的文件。
3。不要在数据库
中存储文件的完整路径在某些时候,您可能会移动文件(可能到另一个驱动器),并且所有存储的文件位置将被破坏。
4。不要在数据库中存储图像URL
与#3相同。如果你的web应用改变了,你想要改变图像url,那么你在数据库中存储了不正确的url。你必须扫描和更新你所有的数据库记录。
5。不要在数据库中存储冗余的路径信息
虽然在数据库中存储的URL中包含"Uploads/Photo/"可能很诱人,但它也有许多问题:
a)这是冗余数据。对于每个文件,您都在使用额外的、不必要的数据空间。b)如果你的应用改变了,URL也应该改变,你存储的URL就会被破坏。
相反,在从数据库读取值后,在URL前加上"Uploads/Photo/"。
更新:
下面是一些示例代码: [HttpPost]
public ActionResult Create(EventModel eventmodel, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
var originalFilename = Path.GetFileName(file.FileName);
string fileId = Guid.NewGuid().ToString().Replace("-", "");
string userId = GetUserId(); // Function to get user id based on your schema
var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), userId, fileId);
file.SaveAs(path);
eventModel.ImageId = fileId;
eventmodel.OriginalFilename = originalFilename;
_db.EventModels.AddObject(eventmodel);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(eventmodel);
}
然而,我会小心使用你的数据模型作为MVC的动作模型。
您应该将您的AvatarUrl更改为:
public HttpPostedFileBase AvatarUrl { get; set; }
在您的视图中,您可以创建一个类似于下面的表单。添加您将接受输入的字段,并为您的头像使用文件输入。当表单发送回控制器时,MVC将尝试将输入绑定到参数。
@using(Html.BeginForm("Create", FormMethod.Post, new { enctype = "multipart/form-data" }) {
<fieldset>
@Html.LabelFor(m => m.FirstName)
@Html.EditorFor(m => m.FirstName)
</fieldset>
<!--
REST OF YOUR INPUT FIELDS HERE
-->
<fieldset>
@Html.LabelFor(m => m.Avatar)
@Html.EditorFor(m => m.Avatar)
</fieldset>
<input type="submit" value="Submit" />
})
你的控制器方法应该更新为:
[HttpPost]
public ActionResult Create(EmployeeModel model)
{
if (ModelState.IsValid)
{
// Create avatar on server
var filename = Path.GetFileName(model.AvatarUrl.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads/Photo/"), filename);
file.SaveAs(path);
// Add avatar reference to model and save
model.AvatarUrl = string.Concat("Uploads/Photo/", filename);
_db.EventModels.AddObject(model);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
如果你仍然卡住了,让我知道,我可以更详细地说明。
也有一个很好的/详细的关于你在这里要做什么的文章http://cpratt.co/file-uploads-in-asp-net-mvc-with-view-models/
如果你使用的是。net 6,你可以这样做:
In Model -
public string? imageFileName { get; set; }
In ViewModel -
public IFormFile? image { get; set; }
在cshtml文件(用户输入表单)-
@model yourViewModel
<input asp-for="image">
In controller/Services -
private readonly IHostEnvironment _hostingEnvironment;
private readonly string _path = "";
Constructor(IHostEnvironment hostingEnvironment){
_hostingEnvironment = hostingEnvironment;
_path = Path.Combine(_hostingEnvironment.ContentRootPath, "wwwroot", "Images");
}
//your method that receives the image {
string fileName = null;
if (image != null) //type of image is IFormFile
{
Guid guid = Guid.NewGuid();
fileName = $"{guid}.{image.FileName.Split('.').Last()}";
await SaveInLocalFolder(image, fileName);
}
//}
private async Task<bool> SaveInLocalFolder(IFormFile file, string fileName)
{
if (!Directory.Exists(_path))
{
Directory.CreateDirectory(_path);
}
using (var fileStream = new FileStream(Path.Combine(_path, fileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
return true;
}
从cshtml文件中像这样访问图像-
<img src="/Images/guid_generated_filename"/>