MVC从字节显示和更新图片

时间:2018-03-16 22:58:58

标签: sql asp.net-mvc database image entity-framework

我正在尝试将编辑功能添加到用户提交的数据库记录中。问题是,混合中有一张图片(如字节)。该图片之前已被裁剪(主要是出于造型原因),当然,用户需要选择a)保留现有图片或b)选择并裁剪新图片。如果用户提交新图片,以下代码可以正常工作,但是如果没有新图片,它将覆盖现有图片而不是保留用户先前上传的图片。

这是我的控制器:

    // POST: EditErrand
    public ActionResult UpdateErrand([Bind(Exclude = "Picture")]EditErrandsViewModel model)
    {
        string newPic = Request.Form["editErrandCroppedPicture"];
        byte[] imageBytes = Convert.FromBase64String(newPic);
        var userId = User.Identity.GetUserId();
        var errand = new EditErrandsViewModel 
        {
            ID = model.ID,
            UserID = User.Identity.GetUserId(),
            FirstName = UserManager.FindById(userId).FirstName,
            Email = UserManager.FindById(userId).Email,
            Phone = UserManager.FindById(userId).PhoneNumber,
            Hometown = UserManager.FindById(userId).Hometown,
            Rating = model.Rating,
            Category = model.Category,
            SubCategory = model.SubCategory,
            Title = model.Title,
            Description = model.Description,
            Location = model.Location,
            ASAP = model.ASAP,
            StartDateTime = model.StartDateTime,
            DurationInHours = model.DurationInHours,
            EndDateTime = model.EndDateTime,
            DateTimePosted = DateTime.UtcNow.ToUniversalTime(),
            Currency = model.Currency,
            Offering = model.Offering,
            Price = model.Price,
            errandTax = model.errandTax,
            PaymentMethod = model.PaymentMethod,
            LatitudePosted = model.LatitudePosted,
            LongitudePosted = model.LongitudePosted,
            LocationPosted = model.LocationPosted,
            UserActivityLatitude = model.LatitudePosted,
            UserActivityLongitude = model.LongitudePosted,
            UserActivityLocation = model.LocationPosted,
            Published = false
        };
        if (imageBytes.Length > 2)
        {
            errand.Picture = imageBytes;
        }
        DB.Entry(errand).State = EntityState.Modified;
        DB.SaveChanges();
        var Success = new UserActivities
        {
            ActivityName = "EditErrand_Success",
            UserID = User.Identity.GetUserId(),
            ActivityTimeStamp = DateTime.Now.ToUniversalTime(),
            ActivityLatitude = model.UserActivityLatitude,
            ActivityLongitude = model.UserActivityLongitude,
            ActivityLocation = model.UserActivityLocation
        };
        DB.UserActivityList.Add(Success);
        DB.SaveChanges();
        return RedirectToAction("errandPreview");
    }

控制器中有以下语句,因为如果用户没有上传文件,它仍会将 0x 写入数据库。

    if (imageBytes.Length > 2)
    {
        errand.Picture = imageBytes;
    }

为了完整起见,我还添加了视图的相关部分,因此您可以了解如何完成裁剪(使用JCrop):

        <div id="editErrandPictureDisplay" class="errandomDisplay col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-4 col-md-7 col-lg-offset-5 col-lg-6">
            <img id="editErrandPicture" class="editErrandPicture" src="@Url.Action("errandPicture", "errandom")" />
        </div>
        <div id="editErrandPictureArea" class="manageArea row">
            @Html.LabelFor(m => m.Picture, new { @id = "editErrandPictureLabel", @class = "manageLabel col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-1 col-md-3 col-lg-offset-1 col-lg-4" })
            <a id="editErrandPictureSelectionButton" class="manageField col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-0 col-md-7 col-lg-offset-0 col-lg-6" href="#">
                select a file...
            </a>
            @Html.TextBoxFor(m => m.Picture, new { @id = "editErrandPictureField", @class = "manageField col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-0 col-md-7 col-lg-offset-0 col-lg-6", @type = "file", @style = "display: none" })
        </div>
        <hr />
        <script>
            jQuery("#editErrandPictureSelectionButton").click(function () {
                $("#editErrandPictureField").click();
                $("#editErrandCroppingArea").show();
            });
        </script>
        <script>
            $("#editErrandPictureField").change(function () {
                var fullFileName = $("#editErrandPictureField").val()
                $("#editErrandPictureSelectionButton").html(fullFileName.substr(fullFileName.lastIndexOf('\\') + 1));
            });
        </script>
        <div id="editErrandCroppingArea" class="manageArea row" style="display: none">
            <img id="editErrandOriginal" class="editErrandImage" src="" alt="" style="display: none" />
            <canvas id="editErrandCropped" class="editErrandImage" height="5" width="5"></canvas>
            <input id="editErrandButtonCrop" class="manageButton col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-1 col-md-10 col-lg-offset-1 col-lg-10" type="button" value="Crop" />
            <input id="editErrandCropX" class="editErrandData" name="editErrandCropX" type="hidden" />
            <input id="editErrandCropY" class="editErrandData" name="editErrandCropY" type="hidden" />
            <input id="editErrandCropW" class="editErrandData" name="editErrandCropW" type="hidden" />
            <input id="editErrandCropH" class="editErrandData" name="editErrandCropH" type="hidden" />
            <input id="editErrandCroppedPicture" class="editErrandData" name="editErrandCroppedPicture" type="hidden" />
        </div>

<script type="text/javascript">
    $(function () {
        if ($('#editErrandCroppingArea').width() > 500) {
            $('#editErrandPictureField').change(function () {
                $('#editErrandOriginal').hide();
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#editErrandOriginal').show();
                    $('#editErrandOriginal').attr("src", e.target.result);
                    $('#editErrandOriginal').Jcrop({
                        onChange: SetCoordinates,
                        onSelect: SetCoordinates,
                        aspectRatio: 1,
                        boxWidth: 450,
                        addClass: 'editErrandCropping'
                    });
                }
                reader.readAsDataURL($(this)[0].files[0]);
            });
        }
        else {
            $('#editErrandPictureField').change(function () {
                $('#editErrandOriginal').hide();
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#editErrandOriginal').show();
                    $('#editErrandOriginal').attr("src", e.target.result);
                    $('#editErrandOriginal').Jcrop({
                        onChange: SetCoordinates,
                        onSelect: SetCoordinates,
                        aspectRatio: 1,
                        boxWidth: 250,
                        addClass: 'editErrandCropping'
                    });
                }
                reader.readAsDataURL($(this)[0].files[0]);
            });
        }
        $('#editErrandButtonCrop').click(function () {
            var x1 = $('#editErrandCropX').val();
            var y1 = $('#editErrandCropY').val();
            var height = $('#editErrandCropH').val();
            var width = $('#editErrandCropW').val();
            var canvas = $("#editErrandCropped")[0];
            var context = canvas.getContext('2d');
            var img = new Image();
            img.onload = function () {
                canvas.height = height;
                canvas.width = width;
                context.drawImage(img, x1, y1, width, height, 0, 0, width, height);
                var image = canvas.toDataURL().replace(/^data:image\/[a-z]+;base64,/, "");
                $('#editErrandCroppedPicture').val(image);
                //$('#editErrandButtonUpload').show();
                $('#editErrandCropped').hide();
                $('#editErrandButtonCrop').hide();
            };
            img.src = $('#editErrandOriginal').attr("src");
        });
    });
    function SetCoordinates(c) {
        $('#editErrandCropX').val(c.x);
        $('#editErrandCropY').val(c.y);
        $('#editErrandCropW').val(c.w);
        $('#editErrandCropH').val(c.h);
        $('#editErrandButtonCrop').show();
    };
</script>

所以最终我的问题是: 如果用户选择新图片(工作正常),如何更新图片?如果用户没有选择新图片,请确保不会覆盖以前上传的图片?现在,所有值将被更新,除了图片(除非选择并裁剪新图片)。

现在添加View Model后,我收到以下错误:

实体类型EditErrandViewModel不是当前上下文的模型的一部分。 描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:

System.InvalidOperationException: The entity type EditErrandViewModel is not part of the model for the current context.

来源错误:

Line 348:                errand.Picture = imageBytes;
Line 349:            }
Line 350:            DB.Entry(errand).State = EntityState.Modified;
Line 351:            DB.SaveChanges();
Line 352:            var Success = new UserActivities

0 个答案:

没有答案