itzick binder
itzick binder

Reputation: 562

Upload File From View to Controller in .net Core

I'm trying to create a .net core project with file upload.

In the model I have a class name "Movie" with 2 properties: Image - of type byte[] and Picture - of type IFormFile.

In the view I added a form with the input:

<input asp-for="Picture" type="file" id="image_upload" />

And in my controller I have a function like that:

public IActionResult NewMovie(Movie movie){...

In the movie object that is passed the property Image and Picture are always NULL.

I tried changing the asp-for from Image to Picture, to change the function to be of type Task, to add IFormFile to the function calling and nothing helped.

I never been able to get the file's data. I need it to be of type byte[] but I'll take anything to help me.

Thank you all in advance.

Upvotes: 2

Views: 6080

Answers (1)

HMZ
HMZ

Reputation: 3127

You dont need to store the image in a byte array your model only needs an IFormFile like this:

Model:

[Required(ErrorMessage = "The {0} field is required")]
[Display(Name = "Image")]
[DataType(DataType.Upload)]
public IFormFile Image { get; set; }

Controller:

if (model.Image == null)
   return View(model);

    string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath,"Your upload path");
    string ImagePath = Guid.NewGuid().ToString() + "_" + model.Image.FileName;
    string filePath = Path.Combine(uploadsFolder, ImagePath);
    using (FileStream fs = new FileStream(filePath, FileMode.Create))
    {
        await model.Image.CopyToAsync(fs);
    }

Add this to your form tag: enctype="multipart/form-data". Its essential for the type="file" input to be submitted.

View:

<form enctype="multipart/form-data" Other attributes...>
  <div class="custom-file">
   <input asp-for="Model.Image" type="file" class="custom-file-input fileUpload" />
   <label class="custom-file-label fileLabel">Choose file</label>
  </div>
  <input type="submit" value="Submit" />
</form>

And finally you save the ImagePath only in your db entity.

Upvotes: 4

Related Questions