[HttpPost]
[ValidateAntiForgeryToken]
public async Task Create([Bind]Employee employee)
{
if (ModelState.IsValid)
{
var files = HttpContext.Request.Form.Files;
foreach (var Image in files)
{
if (Image != null && Image.Length > 0)
{
var file = Image;
var uploads = Path.Combine(_appEnvironment.WebRootPath, "uploads\\img");
if (file.Length > 0)
{
var fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
using (var fileStream = new FileStream(Path.Combine(uploads, fileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
employee.ImageName = fileName;
}
}
}
}
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Edit", new { id = employee.Id,name=employee.FirstName});
}
else
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
}
return View(employee);
}
当我保存图像时,图像在数据库中成功保存,但它需要像C:\Users\VIZO\Desktop\employee.jpg
这样的完整图像路径我不想这样,我需要像这样~images\employee.jpg
保存图像路径文件夹和相同的路径应保存在数据库中,如果有人在保存正确的路径后显示我如何查看该图像。
答案 0 :(得分:0)
您需要创建并保存可在浏览器中使用的路径。像这样
"uploads/img/" + fileName
您在运行时创建的 fileName
。
行动方法已更新
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Create([Bind]Employee employee)
{
string uploadPath = "uploads/img";
if (ModelState.IsValid)
{
var files = HttpContext.Request.Form.Files;
foreach (var file in files)
{
if (file != null && file.Length > 0)
{
var fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
var uploadPathWithfileName = Path.Combine(uploadPath, fileName);
var uploadAbsolutePath = Path.Combine(_appEnvironment.WebRootPath, uploadPathWithfileName);
using (var fileStream = new FileStream(uploadAbsolutePath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
employee.ImageName = uploadPathWithfileName;
}
}
}
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Edit", new { id = employee.Id, name = employee.FirstName });
}
else
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
}
return View(employee);
}