PHP实现将Word文件保存到SQL Server数据库

吾爱主题 阅读:176 2022-11-02 14:27:00 评论:0

算起来,折腾了整整一天,就是完成将上传的Word文件保存到MS SQL Server 2014数据库中。

第一次使用PHP来开发一个小程序,压力也挺大,主要是用户觉得我很快就能完成,这就有点尴尬了,怎么可能?!对于PHP,我还是个新手。

没有办法,只能硬着头皮干了,星期一开始。

原先我一直以为CSDN是最好的开发文档集散地,查资料是首选,结果我查了无数的资料,都没有找到相关的内容,快崩溃了。我发现很多记录日志真是糟糕,写开发日志是为了方便自己也方便别人,胡乱写有什么意义呢?!

只能不停地试,总算是完成了这个小功能。

完成界面:

前端的页面文件:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 <!DOCTYPE html> < html > < head >      < meta charset = "utf-8" >      < title >layui</ title >      < meta name = "renderer" content = "webkit" >      < meta http-equiv = "X-UA-Compatible" content = "IE=edge,chrome=1" >      < meta name = "viewport" content = "width=device-width, initial-scale=1, maximum-scale=1" >      < link rel = "stylesheet" href = "lib/layui-v2.6.3/css/layui.css" rel = "external nofollow"  media = "all" >      < link rel = "stylesheet" href = "css/public.css" rel = "external nofollow"  media = "all" >      < style >          body {              background-color: #ffffff;          }      </ style > </ head > < body > < div class = "layui-form layuimini-form" >      < form action = "" class = "layui-form login-bottom" id = "uploadFile" >                   < div class = "layui-form-item" >              < label class = "layui-form-label required" >模板文件名</ label >              < div class = "layui-input-block" >                  < input type = "text" name = "Dc01" id = "Dc01" lay-verify = "required" lay-reqtext = "模板文件名称"  value = "" class = "layui-input" >              </ div >          </ div >               < div class = "layui-form-item" >              < label class = "layui-form-label required" >简要说明</ label >              < div class = "layui-input-block" >                  < input type = "text" name = "Dc04" id = "Dc04" value = "" class = "layui-input" >              </ div >                 </ div >               < div class = "layui-form-item" style = "border: 0px solid #d70008;" >              < label class = "layui-form-label required" >Word模板</ label >              < div class = "layui-input-inline" style = "width: 600px;" >                  < input type = "text" name = "Dc05" id = "Dc05"  value = "" style = "width: 400px;" class = "layui-input" disabled = "disabled" >              </ div >              < div class = "layui-input-inline" style = "left: -200px;width: 120px;height: 32px;" >                  <!-- <input type="button" value="选择Word文件" id="selectWord" style="width: 120px;height: 32px;"/> -->                  < button type = "button" class = "layui-btn layui-btn-sm layui-btn-normal" style = "width: 100px;height: 39px;" id = "selectWord" >选择Word文件</ button >                  < input type = 'file' id = 'readFile' style = "opacity: 0;border: 0px solid #1e9fff;" >              </ div >                 </ div >            < div class = "layui-form-item" >              < label class = "layui-form-label" >项目名称</ label >              < div class = "layui-input-block" >                  < input type = "text" name = "Dc06"  id = "Dc06" value = "" class = "layui-input" >              </ div >          </ div >            < div class = "layui-form-item" >              < label class = "layui-form-label" >子项目名称</ label >              < div class = "layui-input-block" >                  < input type = "text" name = "Dc07"  id = "Dc07" value = "" class = "layui-input" >              </ div >          </ div >               < div class = "layui-form-item" >              < label class = "layui-form-label" >项目属性</ label >              < div class = "layui-input-inline" >                  < select id = "Dc08" name = "Dc08" lay-filter = "outUnitList" >                      < option value = "日常维护" >服务</ option >                      < option value = "定期巡检" >物质采购</ option >                      < option value = "数据处理" >工程</ option >                  </ select >              </ div >              < label class = "layui-form-label" >适用年度</ label >              < div class = "layui-input-inline" >                  < input type = "text" name = "Dc09"  id = "Dc09" value = "" class = "layui-input" >              </ div >                       </ div >                  < div class = "layui-form-item" >              < label class = "layui-form-label" >上传人</ label >              < div class = "layui-input-inline" >                  < input type = "text" name = "Dc02"  id = "Dc02" value = "" class = "layui-input" >              </ div >              < label class = "layui-form-label" >上传时间</ label >              < div class = "layui-input-inline" >                  < input type = "text" name = "Dc03"  id = "Dc03" value = "" class = "layui-input" >              </ div >                       </ div >                   < div class = "layui-form-item" >              < div class = "layui-input-block" >                  < button class = "layui-btn layui-btn-normal" lay-submit lay-filter = "saveBtn" >确认保存</ button >              </ div >          </ div >                   </ form > </ div > < script src = "lib/layui-v2.6.3/layui.js" charset = "utf-8" ></ script > < script >                       layui.use(['layer','form','rate'], function () {          var form = layui.form, layer = layui.layer, $ = layui.$;            let currentUser='';          let currentDatetime='';          //得到当前的用户名称          $.ajax({              url:'ZTBgetCurrentUser.php',              type:'POST',              async:false,              success:function (data) {                  // $("input[name=C02]").val(data);                  document.getElementById('Dc02').value=data;                  currentUser=data;              }          });                   //得到当前服务器的时间          $.ajax({              url:'ZTBgetServerDatetime.php',              type:'POST',              async:false,              success:function (data) {                  // $("input[name=C02]").val(data);                  document.getElementById('Dc03').value=data;                  document.getElementById('Dc09').value=data.substring(0,4);                               currentDatetime=data;              }          });            document.getElementById('selectWord').addEventListener('click',function(){              $("#readFile").trigger("click");                     });             document.getElementById('readFile').addEventListener('change',function(){              if(this.files.length===0){                  console.log('没有选择文件!');                  return;              }                           let reader=new FileReader();              reader.onload=function (){                  console.log(reader.result);              }              // reader.readAsText(this.files[0]);              // console.log(this.files[0].size);              // console.log(this.files[0].name);              // document.getElementById('Dc05').              document.getElementById('Dc05').value=this.files[0].name;              // console.log(this.files[0].type);          })             // localStorage.clear();          //监听提交          form.on('submit(saveBtn)', function (data) {              data = data.field;                                    //检查数据              var canContinue=true;              var strFalse="";                           var jsonData=[];//准备一个空数组                         var updateData=new Object();//准备对象              updateData.strTable="HtTemplateFile";              updateData.strWhere="c01='"+document.getElementById("Dc01").value+"' and c08='"+document.getElementById("Dc08").value+"' and c09='"+document.getElementById("Dc09").value+"'";              // console.log(updateData);              jsonData.push(updateData);              var json_str=JSON.stringify(jsonData);              $.ajax({//检查数据库ID是否存在                  url:'ZTBIsExist.php',                  data:json_str,                  type:'POST',                  datetype:'json',                  async:false,                  success:function (data) {                      if(data=='YES'){                          canContinue=false;                          strFalse="要插入的记录重复!";                      }                  }              });                if(canContinue){                      // let formID = document.getElementById("uploadFile");                      // let formData = new FormData(formID);//FormData构造器接收的是一个form的DOM对象                      let wordFile = document.getElementById('readFile');                      //用FormData对象对表单数据进行封装                      const fd = new FormData();//FormData构造器接收的是一个form的DOM对象                                      fd.append("wordFile",wordFile.files[0]);//Word文件数据                      fd.append("c01",$('#Dc01').val());//模板文件名                      fd.append("c02",currentUser);//上传人                      fd.append("c03",currentDatetime);//上传时间                      fd.append("c04",$('#Dc04').val());//简要说明                      fd.append("c06",$('#Dc06').val());//项目名称                      fd.append("c07",$('#Dc07').val());//子项目名称                      fd.append("c08",$('#Dc08').val());//项目类型                      fd.append("c09",$('#Dc09').val());//适用年度                                                                                   $.ajax({                                                 url: 'ZTBHTTemplateFileAdd.php',                          type: "POST",                          data: fd,                          dataType: "JSON",                          async: true,                          processData: false,//设置为false,JQuery则不对数据进行序列化                          contentType: false,//设置为false,JQuery则不设Content-Type请求头                          beforeSend: function(xhr){                              console.log('开始!');                                                  },                          complete: function(xhr,status){                              console.log('完成!');                                                  },                          error: function(xhr,status,error){                              console.log('请求出错!');                          },                          success: function(result){                              console.log('表单提交成功!');                          }                      });                        return false;//阻止表单的默认提交事件                                   }             });        }); </ script > </ body > </ html >

后台PHP文件:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 <?php // error_reporting(0); session_start(); $continue =true; $falseStr = "" ;   //获取post的数据 $C01 = $_POST [ 'c01' ]; $C02 = $_POST [ 'c02' ]; $C03 = $_POST [ 'c03' ]; $C04 = $_POST [ 'c04' ];   $C06 = $_POST [ 'c06' ]; $C07 = $_POST [ 'c07' ]; $C08 = $_POST [ 'c08' ]; $C09 = $_POST [ 'c09' ];   if (!isset( $_FILES )){      $returnArr [ 'c05' ]= '没有选择上传的文件' ; } else {      $returnArr [ 'c05' ]= '有文件' ; }   if ( $_FILES [ 'wordFile' ][ 'error' ]>0){      $returnArr [ 'c05' ]= '文件有错误' ; }   $uploadFile = $_FILES [ "wordFile" ]; //得到上传的文件 $wordBlob = file_get_contents ( $uploadFile [ 'tmp_name' ]); file_put_contents ( "123.docx" , $wordBlob , FILE_APPEND); //将文件内容写到磁盘上 //将内容字符串转为十六进制字符串 $wordHexData = "0x" .bin2hex( $wordBlob );   $returnArr [ 'c01' ]= $C01 ; $returnArr [ 'c02' ]= $C02 ; $returnArr [ 'c03' ]= $C03 ; $returnArr [ 'c04' ]= $C04 ;   $returnArr [ 'c06' ]= $C06 ; $returnArr [ 'c07' ]= $C07 ; $returnArr [ 'c08' ]= $C08 ; $returnArr [ 'c09' ]= $C09 ;   //准备写入数据库 require 'ZTBLinkConfig.php' ; //准备插入数据 $sql = "insert into HtTemplateFile(c01,c02,c03,c04,c06,c07,c08,c09,c05) values('$C01','$C02','$C03','$C04','$C06','$C07','$C08','$C09',$wordHexData)" ; $result = $ZTBConn ->query( $sql ); $returnArr [ 'c05' ]= $result ;   //读出来写到磁盘上,这样可以判断上传文件是否真的写入了。 // $sql = "select * from  HtTemplateFile where c01='模板文件名' and c08='项目属性' and c09='2021'"; // $result =$ZTBConn->query($sql); // while($row=$result->fetch()){ //         $hexData= $row['c05']; // }   // $binData=hex2bin($hexData); // file_put_contents("333.docx",$hexData , FILE_APPEND);//将文件内容写到磁盘上   echo json_encode( $returnArr ,JSON_UNESCAPED_UNICODE); ?>

注意点:

1、美化上传按钮

普通的文件上传按钮不好看,与整个界面不协调,放上一个DIV后再放一个LayUI的按钮就可以了,然后使用事件代理,触发实际文件的上传,是change事件。

?
1 2 3 document.getElementById( 'selectWord' ).addEventListener( 'click' , function (){      $( "#readFile" ).trigger( "click" );            });

2、封装上传的数据

使用formData,可以封装整个form。

?
1 2 let formID = document.getElementById( "uploadFile" ); let formData = new FormData(formID); //FormData构造器接收的是一个form的DOM对象

也可以按照要求逐个添加。

?
1 2 3 4 5 6 7 8 9 10 11 12 let wordFile = document.getElementById( 'readFile' ); //用FormData对象对表单数据进行封装 const fd = new FormData(); //FormData构造器接收的是一个form的DOM对象                    fd.append( "wordFile" ,wordFile.files[0]); //Word文件数据 fd.append( "c01" ,$( '#Dc01' ).val()); //模板文件名 fd.append( "c02" ,currentUser); //上传人 fd.append( "c03" ,currentDatetime); //上传时间 fd.append( "c04" ,$( '#Dc04' ).val()); //简要说明 fd.append( "c06" ,$( '#Dc06' ).val()); //项目名称 fd.append( "c07" ,$( '#Dc07' ).val()); //子项目名称 fd.append( "c08" ,$( '#Dc08' ).val()); //项目类型 fd.append( "c09" ,$( '#Dc09' ).val()); //适用年度

既然是对象,最好使用const定义。

完整的上传,使用ajax。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 $.ajax({                             url: 'ZTBHTTemplateFileAdd.php' ,      type: "POST" ,      data: fd,      dataType: "JSON" ,      async: true ,      processData: false , //设置为false,JQuery则不对数据进行序列化      contentType: false , //设置为false,JQuery则不设Content-Type请求头      beforeSend: function(xhr){          console.log( '开始!' );                              },      complete: function(xhr,status){          console.log( '完成!' );                              },      error: function(xhr,status,error){          console.log( '请求出错!' );      },      success: function(result){          console.log( '表单提交成功!' );      } });   return false ; //阻止表单的默认提交事件              }

注意,返回值一定要是JSON格式!!!

3、接收上传的数据,我为了检查数据,是生成在磁盘上,这样就好判断上传的结果,保存到数据库后也是先取出来再写到磁盘上来判断。

保存的时候需要将数据转成16进制的,读取出来就不用再转了!

写入数据库前写入磁盘:

?
1 2 3 4 5 $uploadFile = $_FILES [ "wordFile" ]; //得到上传的文件 $wordBlob = file_get_contents ( $uploadFile [ 'tmp_name' ]); file_put_contents ( "123.docx" , $wordBlob , FILE_APPEND); //将文件内容写到磁盘上 //将内容字符串转为十六进制字符串 $wordHexData = "0x" .bin2hex( $wordBlob );

从数据库中读出来再写入磁盘:

?
1 2 3 4 5 6 7 8 //读出来写到磁盘上,这样可以判断上传文件是否真的写入了。 $sql = "select * from  HtTemplateFile where c01='模板文件名' and c08='项目属性' and c09='2021'" ; $result = $ZTBConn ->query( $sql ); while ( $row = $result ->fetch()){           $hexData = $row [ 'c05' ]; }   file_put_contents ( "333.docx" , $hexData , FILE_APPEND); //将文件内容写到磁盘上

MS SQL Server 2014的文件字段为image。

到此这篇关于PHP实现将Word文件保存到SQL Server数据库的文章就介绍到这了,更多相关PHP Word保存数据库内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/dawn0718/article/details/123138826

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容