需求:将前台获取的数据组成字符串,通过Ajax传送到java后台,在后台中将读取到的字符串保存到本地新建的txt文件中,txt文件按照时间,命名,并且要求文件夹下只能保存一个TXT文件。
function Button1_onclick() { var CVR_IDCard = document.getElementById("CVR_IDCard");//查找文档中ID为CVR_IDCard的元素 var strReadResult = CVR_IDCard.ReadCard();//ReadCard是身份证读取器中的函数 var startTime = new Date().getTime();//的到的是毫秒数。 if(strReadResult == "0") { ClearForm(); document.all['Name'].value = CVR_IDCard.Name; document.all['Sex'].value = CVR_IDCard.Sex; document.all['Nation'].value = CVR_IDCard.Nation; document.all['Born'].value = CVR_IDCard.Born; document.all['Address'].value = CVR_IDCard.Address; document.all['CardNo'].value = CVR_IDCard.CardNo; document.all['IssuedAt'].value = CVR_IDCard.IssuedAt; document.all['EffectedDate'].value = CVR_IDCard.EffectedDate; document.all['ExpiredDate'].value = CVR_IDCard.ExpiredDate; document.all['SAMID'].value = CVR_IDCard.SAMID; document.all['pic'].src = CVR_IDCard.Pic; document.all['Picture'].value = CVR_IDCard.Picture; document.all['PictureLen'].value = CVR_IDCard.PictureLen; //给每个字符串体检关键值,人那会将字符转拼接成一个长字符串 var jsonStr = "Name:"+CVR_IDCard.Name+";Sex:"+CVR_IDCard.Sex+";Nation:"+CVR_IDCard.Nation+ ";Born:"+CVR_IDCard.Born+";Address:"+CVR_IDCard.Address+";CardNo:"+CVR_IDCard.CardNo+ ";IssuedAt:"+CVR_IDCard.IssuedAt+";EffectedDate:"+CVR_IDCard.EffectedDate+";ExpiredDate:" +CVR_IDCard.ExpiredDate;
$.ajax({ url: baseURL + 'CtrlService?action=IDCardImageUpload',type: "POST",data: { TXTDATA:jsonStr,//将长字符串传入后台 txtfileName:"wz"+startTime,//将新的文件名传入后台 }, async:false }); else { ClearForm(); alert(strReadResult); } }
后台Java代码:原文链接:https://www.f2er.com/ajax/161038.htmlpublic Object doCtrlService(StubObject context,JParamObject PO,HttpServletRequest request,HttpServletResponse response) throws Exception { byte[] buffer = "OK".getBytes(); JResponSEObject ro = null; request.setCharacterEncoding("utf-8"); String eaiRoot = EAI.LocalUserHome;//取得是通过容器的实现来取得通过类似post,get等方式传入的数据 String str = request.getParameter("TXTDATA");//将前台的值传到后台 String txtfileName = request.getParameter("txtfileName");//得到以时间命名的文件名 获得文件存储路径 if(eaiRoot.endsWith("/")||eaiRoot.endsWith("\\")) { eaiRoot = eaiRoot.substring(0,eaiRoot.length()-1); } String Separator = System.getProperty("file.separator");//文件分隔符 deleteTXTFile(eaiRoot+Separator+"IDCardReader");//在加载之前先删除原有的txt文件,保证文件夹中只有一个txt文件 String txtPath = eaiRoot+Separator+"IDCardReader/"+txtfileName+".txt";//获取文件路径下的txt文件//明确字符串要存放的路径下的文件 FileWriter fw=new FileWriter(txtPath);//调用write方法,将字符串写入到流中 fw.write(str);//关闭流资源 fw.close(); return null; }//获取到文件夹中后缀为.txt的文件 private void deleteTXTFile(String path) { File file = new File(path); File[] files=file.listFiles();//获取文件列表 for(int i=0;i<files.length;i++) { if(!files[i].isFile()) continue;//如果不是文件就跳过(排除文件夹等) String fileName=files[i].getName();//得到文件名 if(fileName.endsWith(".txt")) { files[i].delete();//后缀名为txt就删除 } } }