将Base64图像发布到Mvc控制器

时间:2017-10-21 13:47:15

标签: javascript c# asp.net ajax asp.net-mvc

考虑这个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 /> 

我想将此src发布到Mvc控制器,但是当使用ajax发布时获取null是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控制器

    [HttpPost]

    public void SaveImage(Image file)
    {

    }

我认为我使用的数据类型对此无效,请告诉我该怎么做。

enter image description here

完整的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>

2 个答案:

答案 0 :(得分:10)

我不是100%确定你的最终目标是什么。但下面的答案解释了如何将base64图像源字符串发送到服务器并保存。我使用从small image (22 KB size)生成的base64字符串对其进行了测试,但它确实有效。

在您的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
});

现在,因为这是图像的基本64字符串,所以使用string作为操作方法的参数类型。参数名称应与formdata项目键(base64Image)匹配。您可以在action方法中从base64字符串生成一个字节数组。此外,图像源以data:image/png;base64,开头,在您尝试转换之前需要从字符串中删除它。

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

Content/Images/

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

答案 1 :(得分:1)

我正在使用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");
        }