PHP: save the uploaded Word file to the MS SQL Server database

Posted by timecatcher on Fri, 25 Feb 2022 11:58:48 +0100

It took a whole day to save the uploaded Word file to the MS SQL Server 2014 database.

It's the first time to use PHP to develop a small program, which is also very stressful. The main reason is that users think I can finish it soon. It's a little embarrassing. How can it be?! For PHP, I'm still a novice.

There's no way but to work hard. It starts on Monday.

Originally, I always thought that CSDN was the best development document distribution center, and checking data was the first choice. As a result, I checked countless data, but I didn't find the relevant content, and I was about to collapse. I found that many log records are really bad. Writing development logs is for the convenience of myself and others. What's the point of writing indiscriminately?!

Can only keep trying, and finally completed this small function.

Completion interface:

Front end page file:

<!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" media="all">
    <link rel="stylesheet" href="css/public.css" 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">Template file name</label>
			<div class="layui-input-block">
				<input type="text" name="Dc01" id="Dc01" lay-verify="required" lay-reqtext="Template file name"  value="" class="layui-input">
			</div>
		</div>
	
		<div class="layui-form-item">
			<label class="layui-form-label required">Brief description</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 Template</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="choice Word file" 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">choice Word file</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">entry name</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">Sub project name</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">Project properties</label>
			<div class="layui-input-inline">
				<select id="Dc08" name="Dc08" lay-filter="outUnitList">
					<option value="Routine maintenance">service</option>
					<option value="Regular patrol inspection">Material procurement</option>
					<option value="data processing">engineering</option>
				</select>
			</div>
			<label class="layui-form-label">Applicable year</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">Uploader</label>
			<div class="layui-input-inline">
				<input type="text" name="Dc02"  id="Dc02" value="" class="layui-input">
			</div>
			<label class="layui-form-label">Upload time</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">Confirm save</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='';
		//Get the current user name
		$.ajax({
			url:'ZTBgetCurrentUser.php',
			type:'POST',
			async:false,
			success:function (data) {
				// $("input[name=C02]").val(data);
				document.getElementById('Dc02').value=data;
				currentUser=data;
			}
		});
		
		//Get the time of the current server
		$.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('No file selected!');
				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();
        //Monitor submission
        form.on('submit(saveBtn)', function (data) {
			data = data.field;			
			
			//Check data
			var canContinue=true;
			var strFalse="";
			
			var jsonData=[];//Prepare an empty array			 
			var updateData=new Object();//Prepare 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({//Check if the database ID exists
				url:'ZTBIsExist.php',
				data:json_str,
				type:'POST',
				datetype:'json',
				async:false,
				success:function (data) {
					if(data=='YES'){ 
						canContinue=false;
						strFalse="Duplicate record to insert!";
					}
				}
			});

			if(canContinue){
					// let formID = document.getElementById("uploadFile");
					// let formData = new FormData(formID);// The formdata constructor receives a DOM object of a form
					let wordFile = document.getElementById('readFile');
					//Encapsulate form data with FormData object
					const fd = new FormData();//The FormData constructor receives a DOM object of a form					
					fd.append("wordFile",wordFile.files[0]);//Word file data
					fd.append("c01",$('#Dc01').val());// Template file name
					fd.append("c02",currentUser);//Uploader
					fd.append("c03",currentDatetime);//Upload time
					fd.append("c04",$('#Dc04').val());// Brief description
					fd.append("c06",$('#Dc06').val());// entry name
					fd.append("c07",$('#Dc07').val());// Sub project name
					fd.append("c08",$('#Dc08').val());// Project type
					fd.append("c09",$('#Dc09').val());// Applicable year
															
					$.ajax({						
						url: 'ZTBHTTemplateFileAdd.php',
						type: "POST",
						data: fd,
						dataType: "JSON",
						async: true,
						processData: false,//Set to false,JQuery will not serialize the data
						contentType: false,//If it is set to false, JQuery does not set the content type request header
						beforeSend: function(xhr){
							console.log('start!');							
						},
						complete: function(xhr,status){
							console.log('complete!');							
						},
						error: function(xhr,status,error){
							console.log('Request error!');
						},
						success: function(result){
							console.log('Form submitted successfully!');
						}
					});

					return false;//Block default submission events for forms				
					}
           });

    });
</script>
</body>
</html>

PHP background files:

<?php
// error_reporting(0);
session_start();
$continue=true;
$falseStr="";

//Get post data
$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']='No files selected for upload';
}else{
	$returnArr['c05']='There are documents';
}

if($_FILES['wordFile']['error']>0){
    $returnArr['c05']='There is an error in the file';
}

$uploadFile = $_FILES["wordFile"];//Get uploaded files
$wordBlob=file_get_contents($uploadFile['tmp_name']);
file_put_contents("123.docx",$wordBlob , FILE_APPEND);//Write file contents to disk
//Convert content string to hexadecimal string
$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;

//Ready to write to database
require 'ZTBLinkConfig.php';
//Ready to insert data
$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;

//Read it out and write it to the disk, so that you can judge whether the uploaded file is really written.
// $SQL = "select * from httemplatefile where C01 = 'template file name' and c08 = 'item attribute' 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);// Write file contents to disk

echo json_encode($returnArr,JSON_UNESCAPED_UNICODE);
?>

Note:

1. Beautify the upload button

The ordinary file upload button is not good-looking and does not coordinate with the whole interface. Just put a DIV and then a LayUI button. Then use the event agent to trigger the upload of the actual file, which is a change event.

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

2. Encapsulate the uploaded data

Using formData, you can encapsulate the entire form.

let formID = document.getElementById("uploadFile");
let formData = new FormData(formID);//The data constructor is a DOM object that receives the form

You can also add one by one as required.

let wordFile = document.getElementById('readFile');
//Encapsulate form data with FormData object
const fd = new FormData();//The FormData constructor receives a DOM object of a form					
fd.append("wordFile",wordFile.files[0]);//Word file data
fd.append("c01",$('#Dc01').val());// Template file name
fd.append("c02",currentUser);//Uploader
fd.append("c03",currentDatetime);//Upload time
fd.append("c04",$('#Dc04').val());// Brief description
fd.append("c06",$('#Dc06').val());// entry name
fd.append("c07",$('#Dc07').val());// Sub project name
fd.append("c08",$('#Dc08').val());// Project type
fd.append("c09",$('#Dc09').val());// Applicable year

Since it is an object, it is best to use const definition.

Complete upload, using ajax.

					$.ajax({						
						url: 'ZTBHTTemplateFileAdd.php',
						type: "POST",
						data: fd,
						dataType: "JSON",
						async: true,
						processData: false,//Set to false,JQuery will not serialize the data
						contentType: false,//If it is set to false, JQuery does not set the content type request header
						beforeSend: function(xhr){
							console.log('start!');							
						},
						complete: function(xhr,status){
							console.log('complete!');							
						},
						error: function(xhr,status,error){
							console.log('Request error!');
						},
						success: function(result){
							console.log('Form submitted successfully!');
						}
					});

					return false;//Block default submission events for forms				
					}

Note that the return value must be in JSON format!!!

3. To receive the uploaded data, I generate the data on the disk in order to check the data, so as to judge the uploaded results. After saving to the database, I also take it out first and then write it to the disk for judgment.

When saving, you need to convert the data into hexadecimal, so you don't have to turn it again after reading it!

Write to disk before writing to database:

$uploadFile = $_FILES["wordFile"];//Get uploaded files
$wordBlob=file_get_contents($uploadFile['tmp_name']);
file_put_contents("123.docx",$wordBlob , FILE_APPEND);//Write file contents to disk
//Convert content string to hexadecimal string
$wordHexData = "0x".bin2hex($wordBlob);

Read from the database and write to disk:

//Read it out and write it to the disk, so that you can judge whether the uploaded file is really written.
$sql = "select * from  HtTemplateFile where c01='Template file name' and c08='Project properties' and c09='2021'";
$result =$ZTBConn->query($sql);
while($row=$result->fetch()){
         $hexData= $row['c05'];
}

file_put_contents("333.docx",$hexData , FILE_APPEND);//Write file contents to disk

The file field of MS SQL Server 2014 is image.

Topics: PHP word