今天用Jquery的jSignature库制作一个电子签名 后台.net core上传到指定文件夹

下载jquery库 提取码:rd9g

html

  1. @{
  2. Layout = null;
  3. }
  4. <!DOCTYPE html>
  5. <html lang="en">
  6. <head>
  7. <meta charset="utf-8">
  8. <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
  9. Remove this if you use the .htaccess -->
  10. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  11. <meta name="viewport" content="initial-scale=1.0, target-densitydpi=device-dpi" /><!-- this is for mobile (Android) Chrome -->
  12. <meta name="viewport" content="initial-scale=1.0, width=device-height"><!-- mobile Safari, FireFox, Opera Mobile -->
  13. <script src="~/lib/jSignature-master/libs/modernizr.js"></script>
  14. <!--[if lt IE 9]>
  15. <script type="text/javascript" src="libs/flashcanvas.js"></script>
  16. <![endif]-->
  17. <style type="text/css">
  18. div {
  19. margin-top: 1em;
  20. margin-bottom: 1em;
  21. }
  22. input {
  23. padding: .5em;
  24. margin: .5em;
  25. }
  26. select {
  27. padding: .5em;
  28. margin: .5em;
  29. }
  30. #signatureparent {
  31. color: darkblue;
  32. background-color: darkgrey;
  33. /*max-width:600px;*/
  34. padding: 20px;
  35. }
  36. /*This is the div within which the signature canvas is fitted*/
  37. #signature {
  38. border: 2px dotted black;
  39. background-color: lightgrey;
  40. }
  41. /* Drawing the \'gripper\' for touch-enabled devices */
  42. html.touch #content {
  43. float: left;
  44. width: 92%;
  45. }
  46. html.touch #scrollgrabber {
  47. float: right;
  48. width: 4%;
  49. margin-right: 2%;
  50. background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAFCAAAAACh79lDAAAAAXNSR0IArs4c6QAAABJJREFUCB1jmMmQxjCT4T/DfwAPLgOXlrt3IwAAAABJRU5ErkJggg==)
  51. }
  52. html.borderradius #scrollgrabber {
  53. border-radius: 1em;
  54. }
  55. </style>
  56. </head>
  57. <body>
  58. <div>
  59. <div id="content">
  60. <input type="button" value="上传" onclick="add()" />
  61. <div id="signatureparent">
  62. <div>jSignature inherits colors from parent element. Text = Pen color. Background = Background. (This works even when Flash-based Canvas emulation is used.)</div>
  63. <div id="signature"></div>
  64. </div>
  65. <div id="tools"></div>
  66. <div><p>Display Area:</p><div id="displayarea"></div></div>
  67. </div>
  68. <div id="scrollgrabber"></div>
  69. </div>
  70. <script src="http://www.jq22.com/jquery/jquery-1.10.2.js"></script>
  71. <script type="text/javascript">
  72. jQuery.noConflict()
  73. </script>
  74. <script>
  75. @*/* @preserve
  76. jQuery pub/sub plugin by Peter Higgins (dante@dojotoolkit.org)
  77. Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.
  78. Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
  79. http://dojofoundation.org/license for more information.
  80. */*@
  81. (function($) {
  82. var topics = {};
  83. $.publish = function(topic, args) {
  84. if (topics[topic]) {
  85. var currentTopic = topics[topic],
  86. args = args || {};
  87. for (var i = 0, j = currentTopic.length; i < j; i++) {
  88. currentTopic[i].call($, args);
  89. }
  90. }
  91. };
  92. $.subscribe = function(topic, callback) {
  93. if (!topics[topic]) {
  94. topics[topic] = [];
  95. }
  96. topics[topic].push(callback);
  97. return {
  98. "topic": topic,
  99. "callback": callback
  100. };
  101. };
  102. $.unsubscribe = function(handle) {
  103. var topic = handle.topic;
  104. if (topics[topic]) {
  105. var currentTopic = topics[topic];
  106. for (var i = 0, j = currentTopic.length; i < j; i++) {
  107. if (currentTopic[i] === handle.callback) {
  108. currentTopic.splice(i, 1);
  109. }
  110. }
  111. }
  112. };
  113. })(jQuery);
  114. </script>
  115. <script src="~/lib/jSignature-master/libs/jSignature.min.noconflict.js"></script>
  116. <script>
  117. (function ($) {
  118. $(document).ready(function () {
  119. // This is the part where jSignature is initialized.
  120. var $sigdiv = $("#signature").jSignature({ \'UndoButton\': true })
  121. // All the code below is just code driving the demo.
  122. , $tools = $(\'#tools\')
  123. , $extraarea = $(\'#displayarea\')
  124. , pubsubprefix = \'jSignature.demo.\'
  125.  
  126. var export_plugins = $sigdiv.jSignature(\'listPlugins\', \'export\')
  127. , chops = [\'<span><b>提取签名数据: </b></span><select>\', \'<option value="">(select export format)</option>\']
  128. , name
  129. for (var i in export_plugins) {
  130. if (export_plugins.hasOwnProperty(i)) {
  131. name = export_plugins[i]
  132. chops.push(\'<option value="\' + name + \'">\' + name + \'</option>\')
  133. }
  134. }
  135. chops.push(\'</select><span><b> or: </b></span>\')
  136. $(chops.join(\'\')).bind(\'change\', function (e) {
  137. if (e.target.value !== \'\') {
  138. var data = $sigdiv.jSignature(\'getData\', e.target.value)
  139. $.publish(pubsubprefix + \'formatchanged\')
  140. if (typeof data === \'string\') {
  141. $(\'textarea\', $tools).val(data)
  142. } else if ($.isArray(data) && data.length === 2) {
  143. $(\'textarea\', $tools).val(data.join(\',\'))
  144. $.publish(pubsubprefix + data[0], data);
  145. } else {
  146. try {
  147. $(\'textarea\', $tools).val(JSON.stringify(data))
  148. } catch (ex) {
  149. $(\'textarea\', $tools).val(\'Not sure how to stringify this, likely binary, format.\')
  150. }
  151. }
  152. }
  153. }).appendTo($tools)
  154. $(\'<input type="button" value="Reset">\').bind(\'click\', function (e) {
  155. $sigdiv.jSignature(\'reset\')
  156. }).appendTo($tools)
  157. $(\'<div><textarea style="width:100%;height:7em;"></textarea></div>\').appendTo($tools)
  158. $.subscribe(pubsubprefix + \'formatchanged\', function () {
  159. $extraarea.html(\'\')
  160. })
  161. $.subscribe(pubsubprefix + \'image/svg+xml\', function (data) {
  162. try {
  163. var i = new Image()
  164. i.src = \'data:\' + data[0] + \';base64,\' + btoa(data[1])
  165. $(i).appendTo($extraarea)
  166. } catch (ex) {
  167. }
  168. var message = [
  169. "If you don\'t see an image immediately above, it means your browser is unable to display in-line (data-url-formatted) SVG."
  170. , "This is NOT an issue with jSignature, as we can export proper SVG document regardless of browser\'s ability to display it."
  171. , "Try this page in a modern browser to see the SVG on the page, or export data as plain SVG, save to disk as text file and view in any SVG-capabale viewer."
  172. ]
  173. $("<div>" + message.join("<br/>") + "</div>").appendTo($extraarea)
  174. });
  175. $.subscribe(pubsubprefix + \'image/svg+xml;base64\', function (data) {
  176. var i = new Image()
  177. i.src = \'data:\' + data[0] + \',\' + data[1]
  178. $(i).appendTo($extraarea)
  179. var message = [
  180. "If you don\'t see an image immediately above, it means your browser is unable to display in-line (data-url-formatted) SVG."
  181. , "This is NOT an issue with jSignature, as we can export proper SVG document regardless of browser\'s ability to display it."
  182. , "Try this page in a modern browser to see the SVG on the page, or export data as plain SVG, save to disk as text file and view in any SVG-capabale viewer."
  183. ]
  184. $("<div>" + message.join("<br/>") + "</div>").appendTo($extraarea)
  185. });
  186. $.subscribe(pubsubprefix + \'image/png;base64\', function (data) {
  187. var i = new Image()
  188. i.src = \'data:\' + data[0] + \',\' + data[1]
  189. $(\'<span><b>As you can see, one of the problems of "image" extraction (besides not working on some old Androids, elsewhere) is that it extracts A LOT OF DATA and includes all the decoration that is not part of the signature.</b></span>\').appendTo($extraarea)
  190. $(i).appendTo($extraarea)
  191. var datapair = $sigdiv.jSignature("getData", "image");
  192. var len = $sigdiv.jSignature(\'getData\', \'native\').length;
  193. if (len > 0) {
  194. $.post(
  195. "/Test/UploadSignature?dt=" + new Date(),
  196. {
  197. imgData: datapair[1]
  198. }, function (res) {
  199. if (res.success) {
  200. alert(\'上传成功!\');
  201. } else {
  202. alert(res.message);
  203. }
  204. }
  205. )
  206. }
  207. else {
  208. alert("请先签名")
  209. }
  210. });
  211. $.subscribe(pubsubprefix + \'image/jsignature;base30\', function (data) {
  212. $(\'<span><b>This is a vector format not natively render-able by browsers. Format is a compressed "movement coordinates arrays" structure tuned for use server-side. The bonus of this format is its tiny storage footprint and ease of deriving rendering instructions in programmatic, iterative manner.</b></span>\').appendTo($extraarea)
  213. });
  214. if (Modernizr.touch) {
  215. $(\'#scrollgrabber\').height($(\'#content\').height())
  216. }
  217. })
  218. })(jQuery)
  219. </script>
  220. </body>
  221. </html>

 

控制器

  1. [HttpPost]
  2. public async Task<IActionResult> UploadSignature()
  3. {
  4. string imgData = HttpContext.Request.Form["imgData"].ToString();
  5. var result = new Dictionary<string, object>();
  6. bool Success = false;
  7. string Message = "";
  8. try
  9. {
  10. var dir = @"./wwwroot/Signature/";
  11. if (!Directory.Exists(dir))
  12. Directory.CreateDirectory(dir);
  13. var fileName = Guid.NewGuid();
  14. var path = dir + fileName + ".jpg";
  15. //using (var fileStream = new FileStream(path, FileMode.Create))
  16. //{
  17. // await file.CopyToAsync(fileStream);
  18. // await fileStream.FlushAsync();
  19. //}
  20.  
  21. byte[] arr = Convert.FromBase64String(imgData);
  22. MemoryStream ms = new MemoryStream(arr);
  23. await ms.FlushAsync();
  24. System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms);
  25. bmp.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
  26. ms.Close();
  27. Success = true;
  28. Message = path.Replace("./wwwroot", string.Empty);
  29. }
  30. catch (Exception ex)
  31. {
  32. Success = false;
  33. Message = ex.Message;
  34. }
  35. result.Add("success", Success);
  36. result.Add("message", Message);
  37. return Json(result);
  38. }

 

版权声明:本文为LiChen19951127原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/LiChen19951127/p/10932300.html