[英]How to set default image in iFormFile, ASP.net Core
我需要设定一个条件,如果用户不想上传图像(IFormFile 文件),那么我可以从控制器设置默认图像。 我怎样才能做到这一点? 我的代码是这样的:
模型
public IFormFile Foto { get; set; }
public string ImagePath { get; set;
控制器
public async Task<IActionResult> Create(Person person,IFormFile file)
{
if (ModelState.IsValid)
{
if (person.BirthYear == 0)
{
person.BirthYear = person.BirthDate.Value.Year;
}
if (file != null && file.Length > 0)
{
var ImagePath = @"/images2/";
var uploadPath = _env.WebRootPath + ImagePath;
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
var uniqFileName = Guid.NewGuid().ToString();
var filename = Path.GetFileName(uniqFileName + "." + file.FileName.Split(".")[1].ToLower());
string fullPath = uploadPath + filename;
ImagePath = ImagePath + @"\";
var filePath = @".." + Path.Combine(ImagePath, filename);
using (var fileStream = new FileStream(fullPath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
string s = Convert.ToBase64String(fileBytes);
person.ImagePath = s;
}
_context.Add(person);
await _context.SaveChangesAsync();
ViewData["FileLocation"] = filePath;
}
return RedirectToRoute(new { controller = "People", action = "Details", id = person.PersonId });
}
return View(person);
}
我已经尝试过这样的:
if (file == null)
{
var fullPath = @"C:\svnProjectos345\sClubeWebEstagio\trunk\sClube\wwwroot\images2\t.png";
using (var fs = new FileStream(fullPath, FileMode.OpenOrCreate))
{
await file.CopyToAsync(fs);
}
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
string s = Convert.ToBase64String(fileBytes);
person.ImagePath = s;
}
_context.Update(person);
await _context.SaveChangesAsync();
}
但是我从await file.CopyToAsync(fs);收到错误(对象引用未设置为对象的实例。) ,有人可以帮我解决这个问题吗? 泰
你写了一个 if 语句
if(file == null){......
你想这样做
await file.CopyToAsync(fs);
它不会工作,因为目标文件为空。
也许你想这样做
if(file != null){......
尝试这个:
if (file == null)
{
//be sure your file path is right
var fileBytes = System.IO.File.ReadAllBytes(@"C:\svnProjectos345\sClubeWebEstagio\trunk\sClube\wwwroot\images2\t.png");
string s = Convert.ToBase64String(fileBytes);
person.ImagePath = s;
_context.Update(person);
await _context.SaveChangesAsync();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.