简体   繁体   中英

How to set default image in iFormFile, ASP.net Core

I need to make a condition that if the user dont wanna upload a image (IFormFile file) then I can set a default image from the controller. How can I make this happen? My code is like this:

Model

public IFormFile Foto { get; set; }

public string ImagePath { get; set; 

Controller

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);
}

I already tryed like this:

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();
}

But im getting error (Object reference not set to an instance of an object.) from await file.CopyToAsync(fs); , some one can help me out this? ty

You wrote an if statement

if(file == null){......

And you want to do this

await file.CopyToAsync(fs);

It wont work because the object file is null.

Maybe you wanted to do this

 if(file != null){......

Try this:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM