在ajax请求中将多张图片上传到服务器

时间:2021-05-10 12:14:42

标签: javascript c# jquery asp.net ajax

我有一个 Web 应用程序,可以创建最多包含 15 个图像和其他数据的帖子,我使用 AJAX 请求在一个请求中发送所有包含图像的数据,但出现此错误:

<块引用>

在使用 JSON JavaScriptSerializer 进行序列化或反序列化过程中发生错误。字符串的长度超过了 MaxJsonLength 属性中设置的值。

我正在尝试在上传之前压缩图像,但仍然存在同样的问题。 这是JS代码:

 function readURL(input) {
    var files = input.files;
    for (var index = 0; index < files.length; index++) {
        var mainImage = "";
        if (files && files[index]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                const imgElement = document.createElement("img");
                imgElement.src = event.target.result;
                if ($(".imgUpload li").length <= 15) {
                    imgElement.onload = function (e) {
                        const canvas = document.createElement("canvas");
                        const MAX_WIDTH = 960;

                        const scaleSize = MAX_WIDTH / e.target.width;
                        canvas.width = MAX_WIDTH;
                        canvas.height = e.target.height * scaleSize;

                        const ctx = canvas.getContext("2d");

                        ctx.drawImage(e.target, 0, 0, canvas.width, canvas.height);

                        const srcEncoded = ctx.canvas.toDataURL(e.target, "image/jpeg");

                        // you can send srcEncoded to the server
                        $(".imgUpload").append('<li class="d-inline-block vTop position-relative mr-3 ' + mainImage + '"><a class="removeImg center w3-text-white fullRadius osRedBg position-absolute" data-ghost="removeImg" href="javascript:;"><svg viewBox="0 0 32 32" width="20" height="20" class="d-inline-block vMiddle" data-name="IconClose"><path fill="#ffffff" stroke="#fff" stroke-width="1" d="M25.333 8.547l-1.88-1.88-7.453 7.453-7.453-7.453-1.88 1.88 7.453 7.453-7.453 7.453 1.88 1.88 7.453-7.453 7.453 7.453 1.88-1.88-7.453-7.453z"></path></svg></a><img class="ad-img" alt="" src="' + srcEncoded + '"></li>');
                         if ($('.imgUpload li.mainImage').length == 0) {
                    $('.imgUpload li:nth-child(2)').addClass("mainImage");
                }

                if ($(".imgUpload li").length > 2) {
                    $(".imgValMsg").text("@Messages.ClickToDetectMainImage");
                }
                    };

                }
                else {
                    $('.modalCountImgs').modal('show');
                }
                if ($('.imgUpload li.mainImage').length == 0) {
                    $('.imgUpload li:nth-child(2)').addClass("mainImage");
                }

                if ($(".imgUpload li").length > 2) {
                    $(".imgValMsg").text("@Messages.ClickToDetectMainImage");
                }

            }

            reader.readAsDataURL(files[index]); // convert to base64 string
        }
    }
}

$("#inputAddImage").change(function () {
    var input = this;
    var files = this.files;
    var validFiles = true;
    for (var index = 0; index < files.length; index++) {
        var extLogo = files[index].name.split('.').pop().toLowerCase();
        if ($.inArray(extLogo, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
            validFiles = false;
            break;
        }

    }
    if (validFiles) {
        readURL(input);
        $("#Imgs-error2").removeClass("d-block").addClass("d-none");
    }
    else {
        $("#Imgs-error2").removeClass("d-none").addClass("d-block");
    }
    $("#Imgs-error").removeClass("d-block").addClass("d-none");
});

和 AJAX 请求:

  //Images
    var lstImgs = [];
    var ImgElements = $(".imgUpload img");
    ImgElements.each(function () {
        var obj = {
            ImageData: $(this).attr("src")
        }
        lstImgs.push(obj);
    });
  
    var productModel = {
        CategoryThirdId: $("#CategoryThirdId").val(),
        ProductTitle: $("#ProductTitle").val(),
        ProductDescription: $("#ProductDescription").val(),
        Price: $("#Price").val(),
      
        Images:lstImgs
    };
            var data = {
                model:productModel
            };
            $.ajax({
                method: "post",
                url: '@Url.Action("CreateAdvertise", "Advertise")',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function (res) {
                    if (res != null) {
                        if (res == "ErrorCatalogName") {
                            $(".danger-product-name").show();
                        }
                    } 
                    else {
                        $(".danger-product-name").hide();
                    }
                    $('#overlay').fadeOut();
                },
                error: function (res) {
                     $('#overlay').fadeOut();
                }
            });

最后,我的目标是将 15 张图像和其他数据从客户端上传到服务器,我使用 ASP .NET MVC 以及要压缩的图像,直到用户上传 20 MB 的图像。

1 个答案:

答案 0 :(得分:0)

您不能将文件作为字符串发布。使用这样的东西:

var fd = new FormData();
fd.append( 'file', input.files[0] );

$.ajax({
url: '/Example/SendData',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});