【问题标题】:Upload multiple images to server in ajax request在ajax请求中将多个图像上传到服务器
【发布时间】:2021-07-31 20:18:28
【问题描述】:

我有一个 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 的图像。

【问题讨论】:

  • 画布的压缩算法非常糟糕,即使你缩小它甚至可以增加图像大小。图像已经被相当压缩了,画布可以与之竞争的是凝灰岩。如果您仍想使用画布,请查看此解决方案:stackoverflow.com/a/51810740/1008999

标签: javascript c# jquery asp.net ajax


【解决方案1】:

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

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);
}
});

【讨论】:

  • 我设置了maxjsonlength=500000000,还是出现同样的问题。
  • 尝试手动设置接收这些文件的方法。 JavaScriptSerializer.MaxJsonLength = 10000000
  • 出现这个错误:非静态字段需要对象引用
  • 从方法中删除static
  • 方法中没有静态,就是方法原型:[HttpPost] public ActionResult CreateAdvertise(ProductDto model)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 2019-12-20
  • 2016-12-13
  • 1970-01-01
  • 2020-07-12
相关资源
最近更新 更多