javascript 将 Base64 图像发布到 Mvc 控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46863910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:59:27  来源:igfitidea点击:

Post Base64 image to Mvc controller

javascriptc#asp.netajaxasp.net-mvc

提问by TAHA SULTAN TEMURI

Consider this base64 encode image

考虑这个 base64 编码图像

<img src='data:image/Png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABICAYAAABhlHJbAAAABHNCSVQICAgIfAhkiAAAAAFzUkdCAK7OHOkAAAAEZ0FNQQAAsY8L/GEFAAAACXBIWXMAABVlAAAVZQGF3cVdAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAABnNJREFUeF7tnFls3EQYx11ucQshClWbtb1LC4RLIARIHAXxgsQDCOWhJGs7mypIoII4BAIhsYAEWY+TlEo8FAQSQjxAuR54AnFUFHH0CQlEEWcaQhpKmx5poVWb8H3eb92Jd7Nre8a7a2d/0l9txvN99vw1HnvtGSsdqskYzu2ayb4A7dNN9oNm2E8qPW8fT5s71EOznDwYdxQ0x0s12LtXD248kaoFpFg8TisMX6Gb9t264dwHSR5PtEz7Mc10BrE92b6RnKLMLaGWulDPO+w3ryLoje8FMlG37As1094IQX/7k6RJqsl+wdNz2WDxVDXProWyGX8dv+qamFu34WQwbz1UPOIPTLec3+HfndXltQU9+P0qE1Vr9GzY+K2/MugACAfUd8q9Mslir4M+BMO+oXb52xpYaOLq1cUTyLziKVCIJvGVtmYMdlf4gTMZ4NkGpjq+NoeTwZ51k8EA+zS/AcaG5z13U0o2zy6FtoqO8ZNKpm/0AvgP350Z7SO1kHlTXJujalqB3vZApQCvSti1aT+pJGcOdUNbZZiHegtP308qBXCJfoL2k0q6+p1LYNzbwRkgoumca /> 

I would like to post this src to Mvc controller but getting null when post with ajax here is the post method.

我想将此 src 发布到 Mvc 控制器,但在使用 ajax 发布时获取空值,这是 post 方法。

    var file = document.getElementById("base64image").src;

        var formdata = new FormData();
        formdata.append("base64image", file);

        $.ajax({
            url: "http://localhost:26792/home/SaveImage",
            type: "POST",
            data: file



        });

Mvc Controller

MVC控制器

    [HttpPost]

    public void SaveImage(Image file)
    {

    }

I think the datatype I am using is not valid for this please suggest me what can I do here.

我认为我使用的数据类型对此无效,请建议我在这里可以做什么。

enter image description here

在此处输入图片说明

Full Html Code

完整的 HTML 代码

<!doctype html>

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
    body { font-family: Helvetica, sans-serif; }
    h2, h3 { margin-top:0; }
    form { margin-top: 15px; }
    form > input { margin-right: 15px; }
    #results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>

<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture &amp; display</h3>

<div id="my_camera"></div>

<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="../webcam.min.js"></script>

<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
    Webcam.set({
        width: 320,
        height: 240,
        image_format: 'jpeg',
        jpeg_quality: 90
    });
    Webcam.attach( '#my_camera' );
</script>

<!-- A button for taking snaps -->
<form>
    <input type=button id="takeshot" value="Take Snapshot" onClick="take_snapshot()">
</form>

<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">

    window.onload = function () {

        setInterval(function () { take_snapshot() }, 5000);
    }
    function take_snapshot() {
        // take snapshot and get image data
        Webcam.snap( function(data_uri) {
            // display results in page
            document.getElementById('results').innerHTML = 
                '<h2>Here is your image:</h2>' + 
                '<img id="base64image" src="' + data_uri + '"/>';
        });



        var file = document.getElementById("base64image").src;

        var formdata = new FormData();
        formdata.append("base64image", file);

        $.ajax({
            url: "http://localhost:26792/home/SaveImage",
            type: "POST",
            data: file



        });
        //var ajax = new XMLHttpRequest();
        //ajax.addEventListener("load", function (event) { uploadcomplete(event); }, false);
        //ajax.open("POST", "http://localhost:26792/home/SaveImage");

        //ajax.send(formdata);
    }
    </script>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


 </body>
 </html>

回答by Shyju

I am not 100 % sure what your end goals are here. But the below answer explains how you can send a base64 image source string to server and save it. I tested it with a base64 string generated from a small image (22 KB size)and it worked.

我不是 100% 确定您的最终目标是什么。但下面的答案解释了如何将 base64 图像源字符串发送到服务器并保存它。我使用从小图像(22 KB 大小)生成的 base64 字符串对其进行了测试,并且它工作正常。

In your ajax call, you should be sending the FormDataobject you created, not the value of filevariable. Also make sure you use processDataand contentTypeproperties when making the ajax call while sending a FormData object.

在您的 ajax 调用中,您应该发送FormData您创建的对象,而不是file变量的值。还要确保在发送 FormData 对象时进行 ajax 调用时使用processDatacontentType属性。

var file = document.getElementById("base64image").src;

var formdata = new FormData();
formdata.append("base64image", file);

$.ajax({
    url: "@Url.Action("SaveImage")",
    type: "POST",
    data: formdata,
    processData: false,
    contentType: false
});

Now since this is the base 64 string of the image, use stringas the parameter type of your action method. The parameter name should match with your formdata item key(base64Image). You can generate a byte array from the base64 string in your action method. Also the image source starts with data:image/png;base64,which needs to be removed from the string before you try to convert it.

现在,由于这是图像的 base 64 字符串,因此请string用作操作方法的参数类型。参数名称应与您的表单数据项键 ( base64Image)匹配。您可以在操作方法中从 base64 字符串生成一个字节数组。此外,data:image/png;base64,在尝试转换之前,需要从字符串中删除图像源。

The below method accepts the string you are sending from the client, and removes the first 21 characters and use the result of that (which is now a valid base 64 string) and then creates an image from that and saves to Content/Images/directory in the app root with a random file name.

下面的方法接受您从客户端发送的字符串,并删除前 21 个字符并使用其结果(现在是有效的 base 64 字符串),然后从中创建一个图像并保存到Content/Images/应用程序根目录中的目录带有随机文件名。

[HttpPost]
public void SaveImage(string base64image)
{
    if (string.IsNullOrEmpty(base64image))
        return;

    var t = base64image.Substring(22);  // remove data:image/png;base64,

    byte[] bytes = Convert.FromBase64String(t);

    Image image;
    using (MemoryStream ms = new MemoryStream(bytes))
    {
        image = Image.FromStream(ms);
    }
    var randomFileName = Guid.NewGuid().ToString().Substring(0, 4) + ".png";
    var fullPath = Path.Combine(Server.MapPath("~/Content/Images/"), randomFileName);
    image.Save(fullPath, System.Drawing.Imaging.ImageFormat.Png);
}

I am not 100 % sure that the default model binder can bind the base64 string to an image. If not, you can perhaps create one which does that and add that to the model binders in your system and then use the Image as the parameter type. The code inside model binder will be very similar ( read the string and generate image from that)

我不是 100% 确定默认模型绑定器可以将 base64 字符串绑定到图像。如果没有,您也许可以创建一个这样做并将其添加到系统中的模型绑定器,然后使用 Image 作为参数类型。模型绑定器中的代码将非常相似(读取字符串并从中生成图像)

回答by Indrit Kello

I am using HttpPostedFileBase.cs.

我正在使用 HttpPostedFileBase.cs。

 [HttpPost]
            public ActionResult AddDocument(ReservationDocumentsVM reservationDocumentsVM, HttpPostedFileBase postedFile)
            {
                if (postedFile != null)
                {
                    string path = Server.MapPath("~/Content/Documents/");

                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    postedFile.SaveAs(path + Path.GetFileName(postedFile.FileName));
                    reservationDocumentsVM.VirtualPath = path + Path.GetFileName(postedFile.FileName);

                    reservationRepository.AddOrUpdateReservationDocuments(reservationDocumentsVM);


                }


   return RedirectToAction("Index", "Reservation");
        }