【问题标题】:Upload cropped image jquery asp.net mvc上传裁剪图像 jquery asp.net mvc
【发布时间】:2020-06-25 19:54:04
【问题描述】:

我可以将用户选择的图像上传到我的项目,但是图像不再被裁剪。 我想上传裁剪后的图像,但上传的图像未裁剪,如何将裁剪后的图像上传到我的 asp.net mvc。保存的图像未裁剪我必须在我的 jquery 代码中进行更改才能上传裁剪的图像而不是普通图像。感谢您的帮助。

我已经习惯了点击链接https://codepen.io/HairyT/pen/axNrdZ来制作用户界面。

这是我的 jquery 代码。

<script id="rendered-js">
    // Requires jQuery
    var imageCrop = function (imageTarget, requiredWidth, requiredHeight) {
        // Variables
        var $doc = $(document),
            $cropMarker,
            $originalImage,
            origSrc = new Image(),
            imageTarget = $(imageTarget).get(0),
            imageScale,
            imageRatio,
            cropRatio,
            adjustedRequiredWidth,
            adjustedRequiredHeight,
            eventState = {},
            allowResize = true,
            keyboardMove = false,
            imageLoaded = new $.Deferred();

        origSrc.crossOrigin = "Anonymous";

        function init() {
            origSrc.onload = function () {
                // Check to make sure the target image is large enough
                if (origSrc.width < requiredWidth || origSrc.height < requiredHeight) {
                    console.log('Image Crop error: The required dimensions are larger than the target image.');
                    return false;
                }

                // And neccessary html
                $(imageTarget).wrap('<div class="ic-container"></div>').before('\
                                    <div class="ic-overlay-n" id="icOverlayN"></div>\
                                    <div class="ic-overlay-e" id="icOverlayE"></div>\
                                    <div class="ic-overlay-s" id="icOverlayS"></div>\
                                    <div class="ic-overlay-w" id="icOverlayW"></div>\
                                    <div class="ic-crop-marker" id="icCropMarker">\
                                        <div class="ic-resize-handle-nw" id="icResizeHandleNW"></div>\
                                        <div class="ic-resize-handle-ne" id="icResizeHandleNE"></div>\
                                        <div class="ic-resize-handle-sw" id="icResizeHandleSW"></div>\
                                        <div class="ic-resize-handle-se" id="icResizeHandleSE"></div>\
                                        <div class="ic-move-handle" id="icMoveHandle"></div>\
                                    </div>\
                                ');
                $cropMarker = $('#icCropMarker');
                $originalImage = $(imageTarget);
                imageScale = origSrc.width / $originalImage.width();
                imageRatio = origSrc.width / origSrc.height;
                cropRatio = requiredWidth / requiredHeight;
                adjustedRequiredWidth = requiredWidth / imageScale;
                adjustedRequiredHeight = requiredHeight / imageScale;

                centerCropMarker();
                repositionOverlay();

                $cropMarker.on('mousedown touchstart', startResize);
                $cropMarker.on('mousedown touchstart', '#icMoveHandle', startMoving);
                imageLoaded.resolve();
            };
            origSrc.src = imageTarget.src;
        };

        function startResize(e) {
            e.preventDefault();
            e.stopPropagation();
            saveEventState(e);
            $doc.on('mousemove touchmove', resizing);
            $doc.on('mouseup touchend', endResize);
        };

        function endResize(e) {
            e.preventDefault();
            $doc.off('mouseup touchend', endResize);
            $doc.off('mousemove touchmove', resizing);
        };

        function resizing(e) {
            var mouse = {},
                width,
                height,
                left,
                top,
                originalWidth = $cropMarker.outerWidth(),
                originalHeight = $cropMarker.outerHeight(),
                originalOffset = $cropMarker.position();
            mouse.x = (e.clientX || e.pageX || e.originalEvent.touches[0].clientX) + $(window).scrollLeft();
            mouse.y = (e.clientY || e.pageY || e.originalEvent.touches[0].clientY) + $(window).scrollTop();

            var SE = false,
                SW = false,
                NW = false,
                NE = false;

            if ($(eventState.evnt.target).is('#icResizeHandleSE')) {
                SE = true;
            } else if ($(eventState.evnt.target).is('#icResizeHandleSW')) {
                SW = true;
            } else if ($(eventState.evnt.target).is('#icResizeHandleNW')) {
                NW = true;
            } else if ($(eventState.evnt.target).is('#icResizeHandleNE')) {
                NE = true;
            }

            if (SE) {
                width = mouse.x - eventState.containerLeft - $originalImage.offset().left;
                height = width / requiredWidth * requiredHeight;
                left = eventState.containerLeft;
                top = eventState.containerTop;
            } else if (SW) {
                width = eventState.containerWidth - (mouse.x - eventState.containerLeft - $originalImage.offset().left);
                height = width / requiredWidth * requiredHeight;
                left = mouse.x - $originalImage.offset().left;
                top = eventState.containerTop;
            } else if (NW) {
                width = eventState.containerWidth - (mouse.x - eventState.containerLeft - $originalImage.offset().left);
                height = width / requiredWidth * requiredHeight;
                left = mouse.x - $originalImage.offset().left;
                top = originalOffset.top + originalHeight - height;
            } else if (NE) {
                width = mouse.x - eventState.containerLeft - $originalImage.offset().left;
                height = width / requiredWidth * requiredHeight;
                left = eventState.containerLeft;
                top = originalOffset.top + originalHeight - height;
            }

            if (
                top >= 0 &&
                left >= 0 &&
                Math.round(top + height) <= Math.round($originalImage.height()) &&
                Math.round(left + width) <= Math.round($originalImage.width())) {
                allowResize = true;
            }

            if (allowResize) {
                // Over top boundary
                if (top < 0) {
                    height = originalHeight + originalOffset.top;
                    width = height / requiredHeight * requiredWidth;
                    top = 0;
                    if (NW) {
                        left = originalOffset.left - (width - originalWidth);
                    }
                    allowResize = false;
                }
                // Over left boundary
                else if (left < 0) {
                    width = originalWidth + originalOffset.left;
                    height = width / requiredWidth * requiredHeight;
                    left = 0;
                    if (SE) {
                        top = originalOffset.top - (height - originalHeight);
                    }
                    allowResize = false;
                }
                // Over bottom boundary
                else if (Math.round(top + height) > Math.round($originalImage.height())) {
                    height = $originalImage.height() - top;
                    width = height / requiredHeight * requiredWidth;
                    if (SW) {
                        left = originalOffset.left - (width - originalWidth);
                    }
                    allowResize = false;
                }
                // Over right boundary
                else if (Math.round(left + width) > Math.round($originalImage.width())) {
                    width = $originalImage.width() - left;
                    height = width / requiredWidth * requiredHeight;
                    if (NE) {
                        top = originalOffset.top - (height - originalHeight);
                    }
                    allowResize = false;
                }

                // Check for min width / height
                if (width > adjustedRequiredWidth && height > adjustedRequiredHeight) {
                    $cropMarker.outerWidth(width).outerHeight(height);
                    $cropMarker.css({
                        'left': left,
                        'top': top
                    });

                } else {
                    if (SW || NW) {
                        left = left - (adjustedRequiredWidth - width);
                    }
                    if (NW || NE) {
                        top = top - (adjustedRequiredHeight - height);
                    }
                    $cropMarker.outerWidth(adjustedRequiredWidth).outerHeight(adjustedRequiredHeight);
                    $cropMarker.css({
                        'left': left,
                        'top': top
                    });

                }
            }
            repositionOverlay();
        }

        function startMoving(e) {
            e.preventDefault();
            e.stopPropagation();
            saveEventState(e);
            $doc.on('mousemove touchmove', moving);
            $doc.on('mouseup touchend', endMoving);
        };

        function endMoving(e) {
            e.preventDefault();
            $doc.off('mouseup touchend', endMoving);
            $doc.off('mousemove touchmove', moving);
        };

        function moving(e) {
            var top,
                left,
                mouse = {},
                touches;
            e.preventDefault();
            e.stopPropagation();

            touches = e.originalEvent.touches;

            mouse.x = (e.clientX || e.pageX || touches[0].clientX) + $(window).scrollLeft();
            mouse.y = (e.clientY || e.pageY || touches[0].clientY) + $(window).scrollTop();

            top = mouse.y - (eventState.mouseY - eventState.containerTop);
            left = mouse.x - (eventState.mouseX - eventState.containerLeft);
            if (top < 0) {
                top = 0;
            }
            if (top + $cropMarker.outerHeight() > $originalImage.height()) {
                top = $originalImage.height() - $cropMarker[0].getBoundingClientRect().height;
            }
            if (left < 0) {
                left = 0;
            }
            if (left + $cropMarker.outerWidth() > $originalImage.width()) {
                left = $originalImage.width() - $cropMarker[0].getBoundingClientRect().width;
            }
            $cropMarker.css({
                'top': top,
                'left': left
            });

            repositionOverlay();
        };

        document.addEventListener('keydown', function (e) {
            var top,
                left,
                shiftAmount,
                top = $cropMarker.position().top,
                left = $cropMarker.position().left;
            if (e.shiftKey) {
                shiftAmount = 10;
            } else {
                shiftAmount = 1;
            }

            if (e.keyCode === 37) {
                left = left - shiftAmount;
            } else if (e.keyCode === 38) {
                top = top - shiftAmount;
            } else if (e.keyCode === 39) {
                left = left + shiftAmount;
            } else if (e.keyCode === 40) {
                top = top + shiftAmount;
            }

            if (top < 0) {
                top = 0;
            }
            if (top + $cropMarker.outerHeight() > $originalImage.height()) {
                top = $originalImage.height() - $cropMarker[0].getBoundingClientRect().width;
            }
            if (left < 0) {
                left = 0;
            }
            if (left + $cropMarker.outerWidth() > $originalImage.width()) {
                left = $originalImage.width() - $cropMarker[0].getBoundingClientRect().width;
            }

            if (keyboardMove) {
                $cropMarker.css({
                    'top': top,
                    'left': left
                });

                repositionOverlay();
            }
        });

        $doc.click(function (e) {
            if ($(e.target).closest('.ic-container').length) {
                keyboardMove = true;
            } else {
                keyboardMove = false;
            }
        });

        var saveEventState = function (e) {
            eventState.containerWidth = $cropMarker.outerWidth();
            eventState.containerHeight = $cropMarker.outerHeight();
            eventState.containerLeft = $cropMarker.position().left;
            eventState.containerTop = $cropMarker.position().top;
            eventState.mouseX = (e.clientX || e.pageX || e.originalEvent.touches[0].clientX) + $(window).scrollLeft();
            eventState.mouseY = (e.clientY || e.pageY || e.originalEvent.touches[0].clientY) + $(window).scrollTop();
            eventState.evnt = e;
        };

        var centerCropMarker = function () {
            if (cropRatio > imageRatio) {
                $cropMarker.outerWidth($originalImage.width());
                $cropMarker.outerHeight($cropMarker.outerWidth() / requiredWidth * requiredHeight);
                $cropMarker.css({
                    top: ($originalImage.height() - $cropMarker.height()) / 2 + 'px',
                    left: 0
                });

            } else {
                $cropMarker.outerHeight($originalImage.height());
                $cropMarker.outerWidth($cropMarker.outerHeight() / requiredHeight * requiredWidth);
                $cropMarker.css({
                    left: ($originalImage.width() - $cropMarker.width()) / 2 + 'px',
                    top: 0
                });

            }
        };

        function repositionOverlay() {
            var imgWidth = $originalImage[0].getBoundingClientRect().width,
                imgHeight = $originalImage[0].getBoundingClientRect().height,
                cropTop = $cropMarker.position().top,
                cropLeft = $cropMarker.position().left,
                cropWidth = $cropMarker[0].getBoundingClientRect().width,
                cropHeight = $cropMarker[0].getBoundingClientRect().height,
                cropBorder = parseFloat($cropMarker.css('border-top-width'));
            $('#icOverlayN').css({
                right: imgWidth - cropLeft - cropWidth,
                height: cropTop,
                left: cropLeft
            });

            $('#icOverlayE').css({
                left: cropLeft + cropWidth
            });

            $('#icOverlayS').css({
                right: imgWidth - cropLeft - cropWidth,
                top: cropTop + cropHeight,
                left: cropLeft
            });

            $('#icOverlayW').css({
                width: cropLeft
            });

        };

        // Crop to required size
        this.crop = function () {
            var cropCanvas,
                img = new Image(),
                scale = origSrc.width / $originalImage.width(),
                left = Math.round($cropMarker.position().left * scale),
                top = Math.round($cropMarker.position().top * scale),
                width = Math.round($cropMarker.outerWidth() * scale),
                height = Math.round($cropMarker.outerHeight() * scale);
            results;

            cropCanvas = document.createElement('canvas');
            cropCanvas.width = requiredWidth;
            cropCanvas.height = requiredHeight;
            cropCanvas.getContext('2d').drawImage(origSrc, left, top, width, height, 0, 0, requiredWidth, requiredHeight);

            img.src = cropCanvas.toDataURL();

            var results = {
                img: img,
                left: left,
                top: top,
                width: width,
                height: height,
                requiredWidth: requiredWidth,
                requiredHeight: requiredHeight
            };

            return results;
        };

        this.position = function (left, top, width, height) {
            $.when(imageLoaded).done(function () {
                var scale = origSrc.width / $originalImage.width();
                left = Math.round(left / scale),
                    top = Math.round(top / scale),
                    width = Math.round(width / scale),
                    height = Math.round(height / scale);
                $cropMarker.outerWidth(width).outerHeight(height);
                $cropMarker.css({
                    'left': left,
                    'top': top
                });

                repositionOverlay();
            });
        };

        this.cropReset = function () {
            centerCropMarker();
            repositionOverlay();
        };

        // Viewport resize
        $(window).resize(function () {
            imageScale = origSrc.width / $originalImage.width();
            adjustedRequiredWidth = requiredWidth / imageScale;
            adjustedRequiredHeight = requiredHeight / imageScale;
            centerCropMarker();
            repositionOverlay();
        });

        init();
    };

    // Initiate Image Crop
    if ($('#exampleImage').length) {
        var exampleCrop = new imageCrop('#exampleImage', 200, 200);
    }

    // Crop event
    $('#exampleCrop').on('click', function () {
        var results = exampleCrop.crop();
        $('body').html(results.img);
    });

    $("#uploadCropedImage").on('click', function () {
        try {
            var formData = new FormData();
            var totalFiles = document.getElementById('fileUpload').files.length;
            for (var i = 0; i < totalFiles; i++) {
                var file = document.getElementById('fileUpload').files[i];
                formData.append("p_file", file);
            }
            $.ajax({
                type: "POST",
                url: '/configuracionGeneral/UploadImage',
                data: formData,
                dataType: 'json',
                contentType: false, // Not to set any content header
                processData: false, // Not to process data
                success: function (result) {
                    alert(result);
                },
                error: function (err) {
                    alert(err.statusText);
                }
            });
        } catch (e) {
            alert("File Upload Error" + e.message);
        }
    });




    $('#drop').on('click', function () {
        $('#fileUpload').trigger('click');
    });

    $('#fileUpload').on('change', function (e) {
        addImage(e.target);
    });

    $("#drop").on("dragover", function (e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).addClass('dragging');
    });

    $("#drop").on("dragleave", function (e) {
        $(this).removeClass('dragging');
    });

    $("#drop").on("drop", function (e) {
        e.preventDefault();
        e.stopPropagation();
        var data = e.dataTransfer || e.originalEvent.dataTransfer;
        addImage(data);
    });

    function addImage(data) {
        var file = data.files[0];
        if (file.type.indexOf('image') === -1) {
            alert('Sorry, the file you uploaded doesn\'t appear to be an image.');
            return false;
        }

        var reader = new FileReader();
        reader.onload = function (event) {
            var img = new Image();
            img.onload = function () {
                if (img.width < 300 || img.height < 300) {
                    alert('Sorry, the image you uploaded doesn\'t appear to be large enough.');
                    return false;
                }
                cropImage(img);
            };
            img.src = event.target.result;
        };
        reader.readAsDataURL(file);
    }

    function cropImage(originalImage) {

        $(originalImage).attr('id', 'fullImage');
        $('#imageResize').html(originalImage);
        $('#sectionDragAndDrop').addClass('hidden');
        $('#sectionResize').removeClass('hidden');

        var newImage = new imageCrop('#fullImage', 600, 600);

        $('#crop').on('click', function () {
            var results = newImage.crop();
            $('#thumbnail').html(results.img);
            $('#sectionResize').addClass('hidden');
            $('#sectionThumbnail').removeClass('hidden');
        });

    }
//# sourceURL=pen.js
</script>

这是我的 asp.net mvc

[HttpPost]
public ActionResult UploadImage(HttpPostedFileBase[] p_file) //HttpPostedFileBase file 
{
    try
    {
        string yourfilepathfolder = "~/Content/images/";
        for (int i = 0; i < Request.Files.Count; i++)
        {
            var file = Request.Files[i];
            var fileName = Path.GetFileName(file.FileName);
            fileName = Guid.NewGuid().ToString() + "_" + fileName;
            var path = Path.Combine(Server.MapPath(yourfilepathfolder), fileName);
            file.SaveAs(path);
        }
        return Json("file has been uploaded");
    }
    catch (Exception ex)
    {
        return Json(null);
    }
}

这是构成我的 UI 的代码

<h3>Logo de la compañía</h3>
<section id="sectionDragAndDrop">
    <div class="drop" id="drop">
        <p>Drag &amp; drop or click here to upload an image.</p>
    </div>
    <input class="file-upload hidden" id="fileUpload" type="file">
</section>

<section class="hidden" id="sectionResize">
    <div class="image-resize" id="imageResize"></div>
    <button class="btn btn-primary" id="crop"><span class="fa fa-crop"></span> Crop</button>
</section>

<section class="hidden" id="sectionThumbnail">
    <div class="thumbnail" id="thumbnail"></div>
    <button class="btn btn-primary" id="uploadCropedImage"><span class="fa fa-crop"></span> Approve and upload</button>
</section>
<div class="space-bottom"></div> 

再次感谢您的帮助。

【问题讨论】:

    标签: jquery asp.net-mvc


    【解决方案1】:

    因为您在以下行发送原始文件:data: formData, 和:

    var formData = new FormData();
    var totalFiles = document.getElementById('fileUpload').files.length;
    for (var i = 0; i < totalFiles; i++) {
       var file = document.getElementById('fileUpload').files[i];
       formData.append("p_file", file);
    }
    

    我可以在代码笔中看到裁剪后的图像,裁剪后的图像是本节下的 base64 图像:

    &lt;div class="thumbnail" id="thumbnail"&gt;&lt;/div&gt;

    所以你应该先提取结果base64代码:

    var ImageURL = $('#thumbnail img').attr('src');
    
    var block = ImageURL.split(";");
    
    var contentType = block[0].split(":")[1];
    
    // get the real base64 content of the file
    var base64 = block[1].split(",")[1];
    
    // Convert it to a blob to upload
    var blob = b64toBlob(base64, contentType);
    
    // Create a FormData and append the file with "image" as parameter name
    var formDataToUpload = new FormData();
    
    formDataToUpload.append("image", blob);
    

    这是将base64转换为blob的函数:

    function b64toBlob(b64Data, contentType, sliceSize) {
            contentType = contentType || '';
            sliceSize = sliceSize || 512;
    
            var byteCharacters = atob(b64Data);
            var byteArrays = [];
    
            for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
                var slice = byteCharacters.slice(offset, offset + sliceSize);
    
                var byteNumbers = new Array(slice.length);
                for (var i = 0; i < slice.length; i++) {
                    byteNumbers[i] = slice.charCodeAt(i);
                }
    
                var byteArray = new Uint8Array(byteNumbers);
    
                byteArrays.push(byteArray);
            }
    
          var blob = new Blob(byteArrays, {type: contentType});
          return blob;
    }
    

    最后在此处将 formDataToUpload 替换为 formData

    $.ajax({
                    type: "POST",
                    url: '/configuracionGeneral/UploadImage',
                    data: formDataToUpload, // replace here
                    dataType: 'json',
                    contentType: false, // Not to set any content header
                    processData: false, // Not to process data
                    success: function (result) {
                        alert(result);
                    },
                    error: function (err) {
                        alert(err.statusText);
                    }
                });
    

    【讨论】:

    • 我已经尝试过您的解决方案,但我收到以下错误“未定义文件上传错误表单”为什么我收到此错误?我添加了生成 UI 的代码,因为我认为您可能需要。非常感谢您的帮助。
    • 在此处删除表单:var formDataToUpload = new FormData(form);。我刚刚编辑了我的答案
    猜你喜欢
    • 2022-01-23
    • 2012-02-28
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    相关资源
    最近更新 更多