Send file as byte[] in Razor view

Viewed 240

Categories.Pictire is byte[]. In <input type="file" asp-for="Picture"/> I2 want to upload picture througt UploadImage like a byte[]. But I get null from view.

<form asp-action="UploadImage" asp-controller="Categories" method="post">
    <div>
        <label asp-for="Picture"></label>
        <span asp-validation-for="Picture"></span><br/>
        <img src='@Url.Action("GetCategoryImage", "Categories", new { id = Model.CategoryId })' /><br/>
        <input asp-for="Picture" />
    </div>
    <br/>
    <div class="form-group">
        <input asp-for="CategoryId" type="hidden" />
        <input type="submit" name="save" class="btn btn-primary" value="Upload" />
    </div>
</form>
public async Task<IActionResult> UploadImage(Category category)
        {
            _db.Get(category.CategoryId).Picture = category.Picture;
            await _db.SaveChangesAsync().ConfigureAwait(false);

            return Redirect("Index");
        }
1 Answers

Firstly,if you want to upload files in form,you need to use enctype="multipart/form-data" in form.And files will not be binded to Picture by default.So you need to get it from Request.Form and convert it to byte[] in controller action.Here is a demo:

View:

<form asp-action="UploadImage" asp-controller="Categories" method="post" enctype="multipart/form-data">
    <div>
        <label asp-for="Picture"></label>
        <span asp-validation-for="Picture"></span><br/>
        <img src='@Url.Action("GetCategoryImage", "Categories", new { id = Model.CategoryId })' /><br/>
        <input asp-for="Picture" />
    </div>
    <br/>
    <div class="form-group">
        <input asp-for="CategoryId" type="hidden" />
        <input type="submit" name="save" class="btn btn-primary" value="Upload" />
    </div>
</form>

Action:

public async Task<IActionResult> UploadImage(Category category)
        {
            var file = Request.Form.Files["Picture"];
            using (var memoryStream = new MemoryStream())
            {
                await file.CopyToAsync(memoryStream);
                category.Picture=memoryStream.ToArray();
            }

            _db.Get(category.CategoryId).Picture = category.Picture;
            await _db.SaveChangesAsync().ConfigureAwait(false);

            return Redirect("Index");
        }

result: enter image description here

Related