简体   繁体   English

无法在MVC操作方法上从base64string创建图像

[英]Not able to create image from base64string on MVC action method

I'm trying to upload image in MVC controller by its content. 我正在尝试按其内容在MVC控制器中上传图像。

$scope.imageUpload = function (event) {
        var files = event.target.files; //FileList object
        fileString = event.target.files[0];
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var reader = new FileReader();
            reader.onload = $scope.imageIsLoaded;
            reader.readAsDataURL(file);
        }
    }
    $scope.imageIsLoaded = function (e) {
        $scope.$apply(function () {
            $scope.userProfilePic = e.target.result;
            $.ajax({
                url: "FileUploadWithAjax",
                type: "POST",
                data: 'imageString=' + e.target.result.split(',')[1],
                processData: false
            });
        });
    }

Once the image is loaded, I'm sending its content to MVC controller. 加载图像后,我会将其内容发送到MVC控制器。

[System.Web.Mvc.HttpPost]
        public void FileUploadWithAjax([FromBody]string imageString)
        {
           bytes = Convert.FromBase64String(imageString);
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                Image image = Image.FromStream(ms);
                image.Save("myBlargyImage.jpg");
            }
        }

But it's breaking while creating image from stream. 但是从流中创建图像时,它正在中断。 It throws an error called "Invalid parameter". 它引发一个错误,称为“无效参数”。

An exception of type 'System.ArgumentException' occurred in System.Drawing.dll but was not handled in user code System.Drawing.dll中发生类型'System.ArgumentException'的异常,但未在用户代码中处理

Additional information: Parameter is not valid. 附加信息:参数无效。

Stack Trace 堆栈跟踪

at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData) at System.Drawing.Image.FromStream(Stream stream) at Micraft.BBraun.Controllers.EmployeeController.FileUploadWithAjax(String imageString) in D:\\B Braun\\mvc 31 JAN 2017\\Micraft.BBraun\\Controllers\\EmployeeController.cs:line 351 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.<>c__DisplayClass1.b__0(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary 2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary 2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) at D:\\ B Braun中的Micraft.BBraun.Controllers.EmployeeController.FileUploadWithAjax(String imageString)的System.Drawing.Image.FromStream(Stream stream)的System.Drawing.Image.FromStream(Stream stream,Boolean useEmbeddedColorManagement,Boolean validateImageData) \\ mvc 2017年1月31日\\ Micraft.BBraun \\ Controllers \\ EmployeeController.cs:第351行位于lambda_method(Closure,ControllerBase,Object []),位于System.Web.Mvc.ActionMethodDispatcher。<> c__DisplayClass1.b__0(ControllerBase控制器,Object [] System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller,Object []参数)在System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext,IDictionary 2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult,ActionInvocation innerInvokeState)处的2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary 2参数) System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult 2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase 1.End() at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f() System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult 2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase 1.End()在System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionResult(IAsyncResult a ),位于System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters。<> c__DisplayClass46.b__3f()处的System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()

UPDATE UPDATE

I was just checking online tool which can generate image from base64string like http://codebeautify.org/base64-to-image-converter 我只是在检查可以从base64string生成图像的在线工具,例如http://codebeautify.org/base64-to-image-converter

When I copied image text from its source in html, I was able to generate Image on above site. 当我从HTML的源代码中复制图像文本时,我能够在上述站点上生成图像。

After that I tried to copy image content which I was getting on my server side method and surprisingly I was not able to generate image. 之后,我尝试复制服务器端方法中获得的图像内容,但令人惊讶的是,我无法生成图像。

Then I compared both texts and found some diferences 然后我比较了两个文本,发现了一些区别

If you check bellow image carefully, I can see some changes like wherever there's any "+" sign in Image content, its replaced with "blank space". 如果您仔细检查波纹管图像,我会看到一些变化,例如图像内容中任何有“ +”号的地方,都用“空白”代替。

is there any content type I'm missing that I should use while posting this data to server? 将数据发布到服务器时,我应该使用什么缺少的内容类型?

右侧数据正常工作(从客户端复制-左侧数据无效从服务器端方法复制)

You need to use encodeURIComponent() on the data sent to server. 您需要在发送到服务器的数据上使用encodeURIComponent() So, in your ajax request, do as follows: 因此,在您的ajax请求中,执行以下操作:

data: 'imageString=' + encodeURIComponent(e.target.result.split(',')[1]),

See AJAX POST and Plus Sign ( + ) -- How to Encode? 参见AJAX POST和加号(+)-如何编码?

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

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