1. 程式人生 > >Asp.Net MVC 中JS通過ajaxfileupload上傳圖片獲取身份證姓名、生日、家庭住址等詳細信息

Asp.Net MVC 中JS通過ajaxfileupload上傳圖片獲取身份證姓名、生日、家庭住址等詳細信息

新手上路 pri virt them boolean tac 識別 multipart utf

客戶要求用身份證圖片上傳獲取身份證的詳細信息就下來研究了一下(現在的客戶真的懶 身份證信息都懶得輸入了哈哈...),經過慢慢研究,果然皇天不負有心人搞出來了。這個借助的是騰訊的一個SKD 騰訊優圖雲人臉服務TencentYoutuYun.SDK.Csharp 這個DLL文件從github下載dll文件,並添加到你項目引用裏,本sdk依賴Newtonsoft.Json,也需一起引用。

1、主要用到裏面的一個封裝類:OCR,現在來看一下裏面的參數信息

技術分享圖片

PlanRegGuest_OCR這個類就封裝了身份證裏面的一下詳細信息

技術分享圖片

其中

public string City { get; set; } 城市

public int? Age { get; set; } 年齡

public string Birthday { get; set; } 生日

public string IDCode { get; set; } 身份證號碼

public string IDName { get; set; } 姓名

public string GuestSex { get; set; } 性別

其他的還在研究中

2、下面在VS2017中新建一個MVC的項目來試一下,開始我用原始的asp.net試了下腦子卡殼了出不來,好久沒寫服務器空間都忘了差不多了...就換了MVC熟悉一點點。

控制器名稱就是People 先看視圖中的內容

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>上傳圖片身份證獲取詳細信息測試</title>
    <script type="text/javascript" src="~/Scripts/jquery-1.9.0.min.js"></script>
    <script src="~/Scripts/ajaxfileupload.js" type="text/javascript"></script>
    <script type="
text/javascript"> function ajaxFileUpload(e) { var files = $(input[name="FileUpload"]).prop(files);//獲取到文件列表 if (files.length == 0) { alert(請選擇文件); return; } $.ajaxFileUpload( { url: /People/IDCodeOcr, //請求地址 secureuri: false, fileElementId: FileUpload, //上傳文件控件ID dataType: text, //可以是json這裏的格式 success: function (data) //成功函數一個異常捕獲一樣 { //返回的數據轉json var obj = $.parseJSON(data); //循環賦值 for (var i = 0; i < obj.length; i++) { var GuestNameDate = $.parseJSON(obj[i]); $("#Name").val(GuestNameDate.name); $("#Address").val(GuestNameDate.address); $("#Birth").val(GuestNameDate.birth); $("#ID").val(GuestNameDate.id); $("#Sex").val(GuestNameDate.sex); $("#Nation").val(GuestNameDate.nation); } }, //異常處理 error: function (data, status, e) { alert("驗證失敗,請上傳身份證照片!"); } } ); } </script> <style> input{border:0px; font-size:28px; font-weight:600; width:1000px;} </style> </head> <body> <br /><br /><br /><br /><br /> <table class="pro_pic_tb"> <tbody> <tr> <td> <p> <span class="input-file"> <input style=" width:1000px; height:50px; font-size:16px;" type="file" name="FileUpload" ID="FileUpload" onchange="javascript:ajaxFileUpload();" /> </span> </p> </td> </tr> </tbody> </table>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名: <input type="text" id="Name" /><br /><br />&nbsp;庭&nbsp;住址: <input type="text" id="Address" /><br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;日: <input type="text" id="Birth" /><br /><br /> 身份證號碼: <input type="text" id="ID" /><br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;別: <input type="text" id="Sex" /><br /><br /> </body> </html>

這裏面就一個文件上傳的跟一個ajaxfileupload.js 引用一下,特別說明一下 網上下載的ajaxfileupload.js已經是很老的了 只有在jQuery 1.4 一下才能用吧 不然會報錯 所以我的ajaxfileupload.js是改過的 我的jQuery是1.9的開始也出錯了,後來換成1.4的還是有問題 低版本的我沒有試過懶得去找了就改js了

ajaxfileupload.js代碼

jQuery.extend({

    createUploadIframe: function (id, uri) {
        //create frame
        var frameId = ‘jUploadFrame‘ + id;
        var iframeHtml = ‘<iframe id="‘ + frameId + ‘" name="‘ + frameId + ‘" style="position:absolute; top:-9999px; left:-9999px"‘;
        if (window.ActiveXObject) {
            if (typeof uri == ‘boolean‘) {
                iframeHtml += ‘ src="‘ + ‘JavaScript:false‘ + ‘"‘;
            }
            else if (typeof uri == ‘string‘) {
                iframeHtml += ‘ src="‘ + uri + ‘"‘;
            }
        }
        iframeHtml += ‘ />‘;
        jQuery(iframeHtml).appendTo(document.body);
        return jQuery(‘#‘ + frameId).get(0);
    },
    createUploadForm: function (id, fileElementId, data) {
        //create form    
        var formId = ‘jUploadForm‘ + id;
        var fileId = ‘jUploadFile‘ + id;
        var form = jQuery(‘<form  action="" method="POST" name="‘ + formId + ‘" id="‘ + formId + ‘" enctype="multipart/form-data"></form>‘);
        if (data) {
            for (var i in data) {
                jQuery(‘<input type="hidden" name="‘ + i + ‘" value="‘ + data[i] + ‘" />‘).appendTo(form);
            }
        }
        var oldElement = jQuery(‘#‘ + fileElementId);
        var newElement = jQuery(oldElement).clone();
        jQuery(oldElement).attr(‘id‘, fileId);
        jQuery(oldElement).before(newElement);
        jQuery(oldElement).appendTo(form);


        //set attributes
        jQuery(form).css(‘position‘, ‘absolute‘);
        jQuery(form).css(‘top‘, ‘-1200px‘);
        jQuery(form).css(‘left‘, ‘-1200px‘);
        jQuery(form).appendTo(‘body‘);
        return form;
    },
    ajaxFileUpload: function (s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout        
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()
        var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == ‘undefined‘ ? false : s.data));
        var io = jQuery.createUploadIframe(id, s.secureuri);
        var frameId = ‘jUploadFrame‘ + id;
        var formId = ‘jUploadForm‘ + id;
        // Watch for a new set of requests
        if (s.global && !jQuery.active++) {
            jQuery.event.trigger("ajaxStart");
        }
        var requestDone = false;
        // Create the request object
        var xml = {}
        if (s.global)
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function (isTimeout) {
            var io = document.getElementById(frameId);
            try {
                if (io.contentWindow) {
                    xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
                    xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;

                } else if (io.contentDocument) {
                    xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
                    xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
                }
            } catch (e) {
                jQuery.handleError(s, xml, null, e);
            }
            if (xml || isTimeout == "timeout") {
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if (status != "error") {
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData(xml, s.dataType);
                        // If a local callback was specified, fire it and pass it the data
                        if (s.success)
                            s.success(data, status);

                        // Fire the global callback
                        if (s.global)
                            jQuery.event.trigger("ajaxSuccess", [xml, s]);
                    } else
                        jQuery.handleError(s, xml, status);
                } catch (e) {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }
                // The request was completed
                if (s.global)
                    jQuery.event.trigger("ajaxComplete", [xml, s]);
                // Handle the global AJAX counter
                if (s.global && ! --jQuery.active)
                    jQuery.event.trigger("ajaxStop");
                // Process result
                if (s.complete)
                    s.complete(xml, status);
                jQuery(io).unbind()
                setTimeout(function () {
                    try {
                        jQuery(io).remove();
                        jQuery(form).remove();

                    } catch (e) {
                        jQuery.handleError(s, xml, null, e);
                    }
                }, 100)
                xml = null
            }
        }
        // Timeout checker
        if (s.timeout > 0) {
            setTimeout(function () {
                // Check to see if the request is still happening
                if (!requestDone) uploadCallback("timeout");
            }, s.timeout);
        }
        try {
            var form = jQuery(‘#‘ + formId);
            jQuery(form).attr(‘action‘, s.url);
            jQuery(form).attr(‘method‘, ‘POST‘);
            jQuery(form).attr(‘target‘, frameId);
            if (form.encoding) {
                jQuery(form).attr(‘encoding‘, ‘multipart/form-data‘);
            }
            else {
                jQuery(form).attr(‘enctype‘, ‘multipart/form-data‘);
            }
            jQuery(form).submit();
        } catch (e) {
            jQuery.handleError(s, xml, null, e);
        }

        jQuery(‘#‘ + frameId).load(uploadCallback);
        return { abort: function () { } };
    },
    uploadHttpData: function (r, type) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if (type == "script")
            jQuery.globalEval(data);
        // Get the JavaScript object, if JSON is used.
        if (type == "json")
            eval("data = " + data);
        // evaluate scripts within html
        if (type == "html")
            jQuery("<div>").html(data).evalScripts();
        return data;
    }, handleError: function (s, xhr, status, e) {
        // If a local callback was specified, fire it
        if (s.error)
            s.error(xhr, status, e);
        // If we have some XML response text (e.g. from an AJAX call) then log it in the console
        else if (xhr.responseText)
            console.log(xhr.responseText);
    }
})

參數我是用JS傳到後臺的控制器中的這裏也可以直接用Form表單 當然各有所愛看自己喜歡的。

3、下面看後臺控制器裏面的代碼 註釋都有了

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using TencentYoutuYun.SDK.Csharp;

namespace MVCPeopleInfoByIDCard.Controllers
{
    public class PeopleController : Controller
    {
        // GET: People
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult IDCodeOcr()
        {
            //獲取上傳圖片
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            if (files.Count == 0) return Json("Faild", JsonRequestBehavior.AllowGet);
            MD5 md5Hasher = new MD5CryptoServiceProvider();
            /*計算指定Stream對象的哈希值*/
            byte[] arrbytHashValue = md5Hasher.ComputeHash(files[0].InputStream);
            //由以連字符分隔的十六進制對構成的String,其中每一對表示value中對應的元素;例如“F-2C-4A”
            string strHashData = System.BitConverter.ToString(arrbytHashValue).Replace("-", "");
            string FileEextension = Path.GetExtension(files[0].FileName);
            string uploadDate = DateTime.Now.ToString("yyyyMMdd");
            string virtualPath = string.Format("/ComponentAttachments/{0}/{1}{2}", uploadDate, strHashData, FileEextension);
            string fullFileName = Server.MapPath(virtualPath);
            //創建文件夾,保存文件
            string path = Path.GetDirectoryName(fullFileName);
            Directory.CreateDirectory(path);
            if (!System.IO.File.Exists(fullFileName))
            {
                files[0].SaveAs(fullFileName);
            }
            //文件名 沒有路徑
            string fileName = files[0].FileName.Substring(files[0].FileName.LastIndexOf("\\") + 1, files[0].FileName.Length - files[0].FileName.LastIndexOf("\\") - 1);
            //文件大小
            string fileSize = GetFileSize(files[0].ContentLength);
            List<string> results = new List<string>();
            //調用dll  實例CR
            OCR ocr = new OCR(fullFileName, 2);
            JsonConvert.SerializeObject(ocr);
            results.Add(ocr.result);
            var obj = Json(results, "text/html", JsonRequestBehavior.AllowGet);
            return obj;

        }
        /// <summary>
        /// 獲取文件大小
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        private string GetFileSize(long bytes)
        {
            long kblength = 1024;
            long mbLength = 1024 * 1024;
            if (bytes < kblength)
                return bytes.ToString() + "B";
            if (bytes < mbLength)
                return decimal.Round(decimal.Divide(bytes, kblength), 2).ToString() + "KB";
            else
                return decimal.Round(decimal.Divide(bytes, mbLength), 2).ToString() + "MB";
        }
    }
}

這裏我前面的data是text類型我就返回 var obj = Json(results, "text/html", JsonRequestBehavior.AllowGet);這個格式。 調試的時候就可以看到基本信息了 在aspx頁面也看到了 就是前臺我取不到 數據 (有時間在研究)、

技術分享圖片

在前臺頁面數據也取到了 看看效果圖,這裏說一下,只是單純的想做功能所以前臺界面沒有寫驗證。文件上傳的類型。還有後臺的一些異常處理我也沒有寫。一般只要是手機拍下來的身份證都可以識別出來的,我試了好幾張了。

技術分享圖片

4、忙活了一天終於搞定了了,網上關於這塊的介紹很少 。紙上得來終覺淺,絕知此事要躬行!有需要源碼的 或者DLL文件的私密我給你。在群文件我已經上傳了。新手上路各位老司機輕噴!!!

Asp.Net MVC 中JS通過ajaxfileupload上傳圖片獲取身份證姓名、生日、家庭住址等詳細信息