Adam
Adam

Reputation: 45

Upload image to database return null or error

For several hours I have been trying to write a code that would allow uploading photos to the database, but either nothing is added to the database or it causes an error:

The [filename] value is not valid

My Restauracja.cs file:

[Required(ErrorMessage = "Wybierz plik")]
[MaxLength(30, ErrorMessage = "vxvxcvcxvxxx")]
[Display(Name = "Zdjecia")]
public string LinkZdjecia { get; set; }

[Display(Name = "Zdjecia")]
public byte[] Photo { get; set; }

Controller RestauracjaController.cs:

public class RestauracjaController : Controller
{
    private readonly FirmaContext _context;

    public RestauracjaController(FirmaContext context)
    {
        _context = context;
    }

   public async Task<IActionResult> Create(Restauracja restauracja, List<IFormFile> Photo)
    {
        foreach (var item in Photo)
        {
            if (item.Length > 0)
            {
                using (var stream = new MemoryStream())
                {
                    await item.CopyToAsync(stream);
                    restauracja.Photo = stream.ToArray();
                }
            }
        }

        return View(restauracja);
    }
}

View Create.cs:

<form asp-action="Create">
  <div class="form-group">
                <label asp-for="LinkZdjecia" class="control-label"></label>
                <input asp-for="LinkZdjecia" class="form-control" />
                <span asp-validation-for="LinkZdjecia" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Photo" class="control-label"></label>
                <input name="Image" id="Imageinput" class="form-control" type="file" />
                <span asp-validation-for="Photo" class="text-danger"></span>
            </div>

            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
</form>

In this case, I got error:

The [filename] value is not valid

In second case, to database is saved null (in Photo). Controller RestauracjaController.cs:

 public async Task<IActionResult> Create(Restauracja restauracja, IFormFile Image)
    {
        if (ModelState.IsValid)
        {
            using (var ms = new MemoryStream())
            {
                Image.CopyTo(ms);
                restauracja.Photo = ms.ToArray();
            }

            _context.Add(restauracja);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(restauracja);
    }

Upvotes: 0

Views: 414

Answers (2)

Racil Hilan
Racil Hilan

Reputation: 25371

Like @T.S. said in the first comment to your question, your code has a lot of potential issues, so it's hard to answer without having to do a full code review which is out of scope on SO. Here are some issues I can see:

  1. the type of Photo should be IFormFile not byte[].

  2. Why does the Create action take a second parameter List<IFormFile> Photo? If you want multiple images, then change make Restauracja.Photo as IEnumerable<IFormFile>, and remove the second parameter in Create. But for now, start with one image, make it work, and then try changing it to multiple images.

  3. Why did you give the input the name Image? There is no such a property in the model. Change it to Photo and use tag helper.

Like this:

<input asp-for="Photo" class="form-control" />

There are other issues, but the above ones will get you going.

Upvotes: 1

mhkarami97
mhkarami97

Reputation: 308

Try this code:

public class RestauracjaController : Controller
{
    private readonly FirmaContext _context;

    public RestauracjaController(FirmaContext context)
    {
        _context = context;
    }

   public async Task<IActionResult> Create(Restauracja restauracja, List<IFormFile> Photo)
    {
        foreach (var item in Photo)
        {
            if (item.Length > 0)
            {
                byte[] result = null;
                using (var readStream = item.OpenReadStream())
                using (var stream = new MemoryStream())
                {
                    readStream.CopyTo(stream);
                    result = readStream.ToArray();

                    //restauracja.Photo = result;
                    //_context.Add(restauracja);
                }
            }
        }

        return View(restauracja);
    }

}

Upvotes: 1

Related Questions