简体   繁体   中英

Not able to create image from base64string on MVC action method

I'm trying to upload image in MVC controller by its content.

$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.

[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

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 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()

UPDATE

I was just checking online tool which can generate image from base64string like 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.

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. So, in your ajax request, do as follows:

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

See AJAX POST and Plus Sign ( + ) -- How to Encode?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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