/*前台代码*/
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GenerateCodeBar.aspx.cs" 2 Inherits="CodeBar_GenerateCodeBar" EnableEventValidation="false" %> 3 4 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 5 <html xmlns="http://www.w3.org/1999/xhtml"> 6 <head runat="server"> 7 <title></title> 8 <meta charset="UTF-8" /> 9 <script src="../js/jquery-1.7.2.min.js" type="text/javascript"></script> 10 <script src="js/html2canvas.js" type="text/javascript"></script> 11 <link href="css/common.css" rel="stylesheet" type="text/css" /> 12 <link href="css/picture.css" rel="stylesheet" type="text/css" /> 13 <link href="../Css/Page.css" rel="stylesheet" type="text/css" /> 14 <script type="text/javascript"> 15 var index = 0; 16 var timer; 17 18 //批量生成条形码 19 function IntervalCodebar() { 20 21 //判断是否已上传附件 22 var SN = $("#hdSN").val(); 23 if (!SN) { 24 alert("请先上传附件"); return false; 25 } 26 $("#content").hide(); 27 index = 0; 28 //每次生成图片时 先清空文件夹下的所有文件 29 var Result = Ajax("post", false, "Handler.ashx", { Option: "d" }, "text"); 30 if (Result == "success") { 31 timer = setInterval(GenerateCodeBar, 1000); 32 } 33 else { 34 alert("生成失败"); 35 } 36 } 37 38 function GenerateCodeBar() { 39 var SN = $("#hdSN").val(); 40 var Model = $("#hdModel").val(); 41 var ProductName = $("#hdProductName").val(); 42 43 var sp_SN = SN.split(','); 44 var sp_Model = Model.split(','); 45 var sp_ProductName = ProductName.split(','); 46 47 if (index >= sp_SN.length) { 48 clearInterval(timer); $("#content").show(); return; 49 } 50 51 $("#txtModel").val(sp_Model[index]); 52 $("#txtSN").val(sp_SN[index]); 53 $("#txtProductName").val(sp_ProductName[index]); 54 cutDiv(sp_Model[index], sp_SN[index]); 55 index++; 56 //setInterval(); 57 } 58 59 //利用Html canvas将Div渲染成图片 60 function cutDiv(Model, SN) { 61 //var contentBox = document.getElementById("contentBox").innerHTML; 62 $.ajax({ 63 type: "post", async: false, url: "Handler.ashx", 64 data: { Option: "a", Model: Model, SN: SN }, datatype: "text", 65 success: function (data) { 66 if (data) { 67 var sp_data = data.split("&SNModel&"); 68 $("#ImgModel_BarCode").html(sp_data[0]); 69 $("#ImgSN_BarCode").html(sp_data[1]); 70 71 html2canvas($("#contentBox"), { 72 allowTaint: true, 73 taintTest: false, 74 onrendered: function (canvas) { 75 canvas.id = "mycanvas"; 76 //document.body.appendChild(canvas); 77 //生成base64图片数据 78 var dataUrl = canvas.toDataURL(); 79 //var newImg = document.createElement("img"); 80 //newImg.src = dataUrl; 81 //document.body.appendChild(newImg); 82 var Result = Ajax("post", false, "Handler.ashx", { Base64Text: dataUrl, Option: "b" }, "text"); 83 if (Result != "success") { 84 alert("生成条形码失败"); return false; 85 } 86 } 87 }) 88 } 89 }, 90 error: function () { 91 } 92 }) 93 } 94 95 /*** 通用Ajax方法 ***/ 96 function Ajax(Type, Async, Url, Data, DataType) { 97 var Result = ""; 98 $.ajax({ 99 type: Type, async: Async, url: Url, 100 data: Data, datatype: DataType, 101 success: function (data) { 102 Result = data; 103 }, 104 error: function () { 105 Result = ""; 106 } 107 }) 108 return Result; 109 } 110 111 //下载文件 112 function DownloadFile() { 113 var Result = Ajax("post", false, "Handler.ashx", { Option: "c" }, "text"); 114 if (Result) { 115 window.open("UploadImage/image.rar"); 116 } 117 } 118 119 120 //检验上传的是否是Excel文件 121 function checkinfo() { 122 var result = false; 123 var str = document.getElementById("fuexecl").value; 124 if (!str) { 125 alert("请选择需要上传的Excel文件"); return false; 126 } 127 var d = /\.[^\.]+$/.exec(str); 128 if (d == ".xlsx" || d == ".xls") { 129 result = true; 130 return result; 131 } 132 else { 133 alert("请上传Excel文件"); return false; 134 } 135 } 136 </script> 137 </head> 138 <body> 139 <form id="Form1" runat="server"> 140 <div id="content" style="height: 38px;"> 141 <table border="0" cellspacing="1" cellpadding="3" class="table" align="right" style="min-width: 980px"> 142 <tr> 143 <td width="250px" align="right"> 144 请选择需要生成条形码的Excel数据: 145 </td> 146 <td class="tddt" width="150px"> 147 <input runat="server" type="file" class="input" id="fuexecl" /> 148 </td> 149 <td align="left"> 150 <asp:Button runat="server" class="button" ID="btnSend" Text="上 传" OnClientClick="return checkinfo();" 151 OnClick="btnSend_Click" /> 152 <input type="button" id="btnCutDiv" class="button" value="生成条形码" style="margin-left: 10px;" 153 onclick="IntervalCodebar()" /> 154 <input type="button" id="btnDownload" class="button" value="下 载" style="margin-left: 10px;" 155 onclick="DownloadFile()" /> 156 </td> 157 </tr> 158 </table> 159 </div> 160 <div class="contentBox" id="contentBox"> 161 <div class="one"> 162 <div class="one_log"> 163 </div> 164 </div> 165 <div class="nine"> 166 <input type="text" id="txtProductName" class="textIpt1" /> 167 </div> 168 <div class="two"> 169 <span>型号:</span> 170 <input type="text" id="txtModel" class="textIpt1" /> 171 </div> 172 <div class="three" style="margin-left: 30px;"> 173 <literal id="ImgModel_BarCode"></literal> 174 </div> 175 <div class="four"> 176 <span>SN:</span> 177 <input type="text" id="txtSN" class="textIpt1" /> 178 </div> 179 <div class="five" style="margin-left: 30px;"> 180 <literal id="ImgSN_BarCode"></literal> 181 </div> 182 <div class="ten"> 183 <img src="images/1.png" alt=""> 184 </div> 185 <div class="ele"> 186 <img src="images/11.png" alt=""> 187 </div> 188 </div> 189 <input type="hidden" runat="server" id="hdSN" /> 190 <input type="hidden" runat="server" id="hdModel" /> 191 <input type="hidden" runat="server" id="hdProductName" /> 192 </form> 193 </body> 194 </html>
/*后台代码*/
1 <%@ WebHandler Language="C#" Class="Handler" %> 2 3 using System; 4 using System.Collections.Generic; 5 using System.Linq; 6 using System.Web; 7 using System.Web.UI; 8 using System.Web.UI.WebControls; 9 using System.Drawing; 10 using System.Drawing.Imaging; 11 using ThoughtWorks.QRCode.Codec; 12 using ThoughtWorks.QRCode.Codec.Data; 13 using System.Drawing.Drawing2D; 14 using System.Text; 15 using System.IO; 16 17 18 public class Handler : IHttpHandler 19 { 20 21 public void ProcessRequest(HttpContext context) 22 { 23 string Option = context.Request.Form["Option"]; 24 25 switch (Option) 26 { 27 //生成Code39 编码 28 case "a": 29 string Model = context.Request.Form["Model"];//型号 30 string SN = context.Request.Form["SN"];//SN号 31 string CodeBarModel = BarCodeHelper.get39(Model.Trim(), 1, 40); 32 string CodeBarSN = BarCodeHelper.get39(SN.Trim(), 1, 40); 33 context.Response.Write(CodeBarModel + "&SNModel&" + CodeBarSN); 34 context.Response.End(); 35 break; 36 37 //根据Base64编码生成图片 38 case "b": 39 string Base64Text = context.Request.Form["Base64Text"].Replace("data:image/png;base64,", "");//Base64文本 40 string Result = ""; 41 if (Base64StringToImage(context, Base64Text)) 42 Result = "success"; 43 else 44 Result = "error"; 45 context.Response.Write(Result); 46 context.Response.End(); 47 break; 48 49 //把文件夹下的所有文件打包成压缩包 50 case "c": 51 string path = context.Server.MapPath("~/CodeBar/UploadImage/"); //文件夹路径 52 string[] filesOrDirectoriesPaths = Directory.GetFiles(path); //获取文件夹下全部文件路径 53 //List<FileInfo> files = new List<FileInfo>(); 54 //foreach (string filepath in paths) 55 //{ 56 // FileInfo file = new FileInfo(filepath); //获取单个文件 57 // files.Add(file); 58 //} 59 string strZipPath = path + "image.rar";//生成的zip文件的路径 60 string strZipTopDirectoryPath = path;//源文件的上级目录 61 int intZipLevel = 6;//T压缩等级 62 string strPassword = "";//压缩包解压密码 63 if (Zip(strZipPath, strZipTopDirectoryPath, intZipLevel, strPassword, filesOrDirectoriesPaths)) 64 { 65 context.Response.Write(strZipPath); context.Response.End(); 66 } 67 break; 68 69 //删除文件夹下的所有文件 70 case "d": 71 path = context.Server.MapPath("~/CodeBar/UploadImage/"); //文件夹路径 72 string[] paths = Directory.GetFiles(path); //获取文件夹下全部文件路径 73 List<FileInfo> files = new List<FileInfo>(); 74 string result = ""; 75 if (paths.Length == 0) 76 result = "success"; 77 else 78 { 79 try 80 { 81 foreach (string filepath in paths) 82 { 83 FileInfo file = new FileInfo(filepath); //获取单个文件 84 file.Delete(); 85 } 86 result = "success"; 87 } 88 catch (Exception ex) 89 { 90 result = "error"; 91 throw; 92 } 93 } 94 context.Response.Write(result); context.Response.End(); 95 break; 96 } 97 98 } 99 100 public bool IsReusable 101 { 102 get 103 { 104 return false; 105 } 106 } 107 108 /// <summary> 109 /// 生成压缩文件 110 /// </summary> 111 /// <param name="strZipPath">生成的zip文件的路径</param> 112 /// <param name="strZipTopDirectoryPath">源文件的上级目录</param> 113 /// <param name="intZipLevel">T压缩等级</param> 114 /// <param name="strPassword">压缩包解压密码</param> 115 /// <param name="filesOrDirectoriesPaths">源文件路径</param> 116 /// <returns></returns> 117 private bool Zip(string strZipPath, string strZipTopDirectoryPath, int intZipLevel, string strPassword, string[] filesOrDirectoriesPaths) 118 { 119 try 120 { 121 List<string> AllFilesPath = new List<string>(); 122 if (filesOrDirectoriesPaths.Length > 0) // get all files path 123 { 124 for (int i = 0; i < filesOrDirectoriesPaths.Length; i++) 125 { 126 if (File.Exists(filesOrDirectoriesPaths[i])) 127 { 128 AllFilesPath.Add(filesOrDirectoriesPaths[i]); 129 } 130 else if (Directory.Exists(filesOrDirectoriesPaths[i])) 131 { 132 GetDirectoryFiles(filesOrDirectoriesPaths[i], AllFilesPath); 133 } 134 } 135 } 136 137 if (AllFilesPath.Count > 0) 138 { 139 140 ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(strZipPath)); 141 zipOutputStream.SetLevel(intZipLevel); 142 zipOutputStream.Password = strPassword; 143 144 for (int i = 0; i < AllFilesPath.Count; i++) 145 { 146 string strFile = AllFilesPath[i].ToString(); 147 try 148 { 149 if (strFile.Substring(strFile.Length - 1) == "") //folder 150 { 151 string strFileName = strFile.Replace(strZipTopDirectoryPath, ""); 152 if (strFileName.StartsWith("")) 153 { 154 strFileName = strFileName.Substring(1); 155 } 156 ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(strFileName); 157 entry.DateTime = DateTime.Now; 158 zipOutputStream.PutNextEntry(entry); 159 } 160 else //file 161 { 162 FileStream fs = File.OpenRead(strFile); 163 164 byte[] buffer = new byte[fs.Length]; 165 fs.Read(buffer, 0, buffer.Length); 166 167 string strFileName = strFile.Replace(strZipTopDirectoryPath, ""); 168 if (strFileName.StartsWith("")) 169 { 170 strFileName = strFileName.Substring(0); 171 } 172 ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(strFileName); 173 entry.DateTime = DateTime.Now; 174 zipOutputStream.PutNextEntry(entry); 175 zipOutputStream.Write(buffer, 0, buffer.Length); 176 177 fs.Close(); 178 fs.Dispose(); 179 } 180 } 181 catch 182 { 183 continue; 184 } 185 } 186 187 zipOutputStream.Finish(); 188 zipOutputStream.Close(); 189 190 return true; 191 } 192 else 193 { 194 return false; 195 } 196 } 197 catch 198 { 199 return false; 200 } 201 } 202 203 /// <summary> 204 /// Gets the directory files. 205 /// </summary> 206 /// <param name="strParentDirectoryPath">源文件路径</param> 207 /// <param name="AllFilesPath">所有文件路径</param> 208 private void GetDirectoryFiles(string strParentDirectoryPath, List<string> AllFilesPath) 209 { 210 string[] files = Directory.GetFiles(strParentDirectoryPath); 211 for (int i = 0; i < files.Length; i++) 212 { 213 AllFilesPath.Add(files[i]); 214 } 215 string[] directorys = Directory.GetDirectories(strParentDirectoryPath); 216 for (int i = 0; i < directorys.Length; i++) 217 { 218 GetDirectoryFiles(directorys[i], AllFilesPath); 219 } 220 if (files.Length == 0 && directorys.Length == 0) //empty folder 221 { 222 AllFilesPath.Add(strParentDirectoryPath); 223 } 224 } 225 226 227 /// <summary> 228 /// base64编码的文本 转为 图片 229 /// </summary> 230 /// <param name="txtFileName"></param> 231 private bool Base64StringToImage(HttpContext context, string Base64Text) 232 { 233 bool IsSuccess = false; 234 try 235 { 236 byte[] arr = Convert.FromBase64String(Base64Text); 237 MemoryStream ms = new MemoryStream(arr); 238 Bitmap bmp = new Bitmap(ms); 239 240 string GUID = System.Guid.NewGuid().ToString(); 241 string path = context.Server.MapPath("~/CodeBar/UploadImage/"); 242 //判断是否存在文件夹 不存在则创建 243 if (!Directory.Exists(path)) 244 { 245 Directory.CreateDirectory(path); 246 } 247 248 bmp.Save(path + GUID + ".png", System.Drawing.Imaging.ImageFormat.Png); 249 ms.Close(); 250 IsSuccess = true; 251 } 252 catch (Exception ex) 253 { 254 IsSuccess = false; 255 } 256 return IsSuccess; 257 } 258 259 }