简体   繁体   English

使用.NET Core 2.2上传图像

[英]Upload an Image with .NET Core 2.2

I have a form that displays the current data of a member, including his picture. 我有一个显示成员当前数据的表格,包括他的照片。 Below his photo, he can choose to upload another and I replace the old photo in with the new photo in my controller. 在他的照片下方,他可以选择上传另一张照片,然后我将旧照片替换为控制器中的新照片。

My problem is that I can not recover the image in my model, it is always null (the rest goes perfectly). 我的问题是我无法恢复模型中的图像,该图像始终为空(其余图像进行得很完美)。

In my model, I declared a Member_UploadPicture variable of type IFormFile . 在我的模型,我宣布一个Member_UploadPicture类型的变量IFormFile

I followed the recent Microsoft tutorial ( https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.2 ) but nothing works, still null . 我遵循了最近的Microsoft教程( https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.2 ),但没有任何效果,仍然为null。

I tried with an @Html.Editor with the name of the variable and also with an <input type = file> but the 2 are always null. 我尝试使用带有变量名称的@Html.Editor以及<input type = file>但是2始终为null。

Do you have an idea? 你有想法吗?

Model 模型

public class MemberViewModel
{
    public string Member_NameFirst { get; set; }
    public string Member_NameLast { get; set; }

    public byte[] Member_Picture { get; set; }
    public IFormFile Member_UploadPicture { get; set; }
    public string Member_Picture_Show { get; set; }

    // other properties...
}

Controller 控制者

[Authorize(Roles = "Member, Admin")]
[HttpPost]
public async Task<IActionResult> GetMember(MemberViewModel model)
{
    if (ModelState.IsValid)
    {
        var MembertoUpdate = new MemberViewModel
        {
          //code
        };

        using (var memomyStream = new MemoryStream())
        {
            await model.Member_UploadPicture.CopyToAsync(memomyStream);
            MembertoUpdate.Member_Picture = memomyStream.ToArray();
        }
        return Ok(model);
    }
    else return BadRequest();
}

View 视图

    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "formAll", style = "margin-top:3%", enctype = "multipart/form-data" }))
    {
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h3 class="panel-title">Personnal</h3>
            </div>
            <div class="panel-body">
                <div id="formMember" class="row col-xs-12">
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                    <div class="col-xs-6">
                        <div class="form-check-inline col-xs-12" style="margin-top:2%">
                            <img id="ItemPreview" src="data:image/png;base64, @Model.Member_Picture_Show" style="height:200px; width:200px; margin-left:35%; border:solid 1px black">
                        </div>
                        <div class="form-check-inline col-xs-12" style="margin-top:2%; margin-left:35%">
                            @Html.LabelFor(model => model.Member_UploadPicture, "Upload Picture", new { htmlAttributes = new { @id = "test" } })
                            @Html.EditorFor(model => model.Member_UploadPicture, new { htmlAttributes = new { @class = "form-control-file", @id = "Member_UploadPicture" } })
                            <input type="file" class="form-control-file" name="Member_UploadPicture" id="Member_UploadPicture">
                            <small id="fileHelp" class="form-text text-muted">Maximum 1024kb</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
}

Ajax Call 阿贾克斯电话

function Edit() {

    $(function () {
        $("#formAll").submit(function (event) {
            event.preventDefault();

            var formData = $("#formAll").serialize();

            $.ajax({
                url: "https://localhost:44338/Members/GetMember/",
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function (data) {
                    //code
                },
                error: function (error) {
                    //code
                }
            });
        })
    });
}

For var formData = $("#formAll").serialize(); 对于var formData = $("#formAll").serialize(); , it is not able to serialize IFormFile , you need to append IFormFile to formData . ,它无法序列化IFormFile ,需要将IFormFile追加到formData

<script type="text/javascript">
    $(document).ready(function () {
        $("#formAll").submit(function (event) {
            event.preventDefault();

            var formData = new FormData();
            formData.append('Member_NameFirst', $('#Member_NameFirst').val());
            formData.append('Member_UploadPicture', $('#Member_UploadPicture')[0].files[0]);
        $.ajax({
                url: "https://localhost:44307/home/getmember",
                type: 'POST',
                data: formData,
                dataType: 'json',
                processData: false,
                contentType: false,
                success: function (data) {
                    //code
                },
                error: function (error) {
                    //code
                }
            });
        })        })
</script>

remove 去掉

@Html.EditorFor(model => model.Member_UploadPicture, new { htmlAttributes = new { @class = "form-control-file", @id = "Member_UploadPicture" } })

add to you ajax request 添加到您的ajax请求

processData: false,
contentType: false,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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