如何在保存上传图片时添加refno前缀至文件名?
问题描述
我的网站有随机生成的refno编号(示例:20221234),同时具备文件上传功能。目前上传的图片会以原文件名(如cat.png)保存到指定路径,我想在保存图片时把refno加在文件名前缀,变成20221234cat.png的格式,请问是否可行?
现有代码
PHP上传代码
<?php $refno = isset ($_GET['refno'])? $_GET['refno']:''; $file = isset($_FILES["file"]["tmp_name"])? $_FILES["file"]["tmp_name"] : ""; $file_size = isset($_FILES["file"]["size"])? $_FILES["file"]["size"] : ""; $file_name = isset($_FILES["file"]["name"])? $_FILES["file"]["name"] : ""; if(isset($_POST['submit'])) { $dataDir = "//sgewsnant21.amk.st.com/ews/web/webspool/temp/visualdefectreport/"; if ($file_size <= 0) { echo "<script language=\"javascript\" type=\"text/javascript\">"; echo " alert('No picture attached!')"; //echo $refno; echo "</script>"; } else { if(stristr($file_name, ".png")){ $connection = mysqli_connect($apews_db_apews2, $apews_db_usr, $apews_db_pwd) or die ("Unableeeee to connect!"); $dest = $dataDir.$file_name; if(move_uploaded_file($file,$dest)) { echo "<script language=\"javascript\" type=\"text/javascript\">"; echo " alert('Visual Defect Report and pictures are successfully submitted!')"; //echo $refno; echo "</script>"; } } else if(stristr($file_name, ".jpg")){ $connection = mysqli_connect($apews_db_apews2, $apews_db_usr, $apews_db_pwd) or die ("Unableeeee to connect!"); $dest = $dataDir.$file_name; if(move_uploaded_file($file,$dest)) { echo "<script language=\"javascript\" type=\"text/javascript\">"; echo " alert('Visual Defect Report and pictures are successfully submitted!')"; //echo $refno; echo "</script>"; } } else if(stristr($file_name, ".jpeg")){ $connection = mysqli_connect($apews_db_apews2, $apews_db_usr, $apews_db_pwd) or die ("Unableeeee to connect!"); $dest = $dataDir.$file_name; if(move_uploaded_file($file,$dest)) { echo "<script language=\"javascript\" type=\"text/javascript\">"; echo " alert('Visual Defect Report and pictures are successfully submitted!')"; //echo $refno; echo "</script>"; } } } } $file_name= "//sgewsnant21.amk.st.com/ews/web/webspool/temp/visualdefectreport/" . $refno.$file_name; flush(); mysqli_close($conn); ?>
前端生成refno代码
<script type="text/javascript"> const now = new Date(); let randomNum = ''; randomNum += Math.round(Math.random() * 9); randomNum += Math.round(Math.random() * 9); randomNum += now.getTime().toString().slice(-2); window.onload = function () { document.getElementById("refno").value = `${new Date().getFullYear()}${randomNum}`; } </script> <label class="control-label col-sm-4" for="refno">REF nos :</label> <div class="col-sm-4"> <p class="form-control-static" style="margin-top: -6px;"> <input type="text" class="form-control" id="refno" name="refno" value="<?php echo $refno;?>" disabled> </p> </div>
解决方案
完全可行,只需修改几个关键节点,同时优化现有代码的冗余问题:
1. 修正refno的获取逻辑
当前代码用$_GET['refno']获取值,但表单提交是POST方法,且前端refno输入框为disabled状态——disabled的输入框不会随表单提交数据,需做两处修改:
- 前端:将
<input ... disabled>改为<input ... readonly>,确保值能提交且用户无法修改 - 后端:将
$refno = isset ($_GET['refno'])? $_GET['refno']:'';改为$refno = isset($_POST['refno']) ? trim($_POST['refno']) : '';
2. 拼接refno到文件名前缀
在生成文件保存路径$dest时,直接将$refno与原文件名拼接,替换原代码中的$dataDir.$file_name为$dataDir . $refno . $file_name即可得到目标格式。
3. 优化冗余代码
原代码对不同图片后缀做了重复逻辑,可合并判断;同时数据库连接只需执行一次,无需在每个分支重复编写。
完整修改后的PHP代码
<?php $refno = isset($_POST['refno']) ? trim($_POST['refno']) : ''; $file = isset($_FILES["file"]["tmp_name"]) ? $_FILES["file"]["tmp_name"] : ""; $file_size = isset($_FILES["file"]["size"]) ? $_FILES["file"]["size"] : ""; $file_name = isset($_FILES["file"]["name"]) ? $_FILES["file"]["name"] : ""; if(isset($_POST['submit'])) { $dataDir = "//sgewsnant21.amk.st.com/ews/web/webspool/temp/visualdefectreport/"; if ($file_size <= 0) { echo "<script language='javascript'>alert('No picture attached!');</script>"; } else { // 定义允许的图片后缀集合 $allowedExts = ['.png', '.jpg', '.jpeg']; $fileExt = strtolower(strrchr($file_name, '.')); // 判断文件后缀是否合法 if(in_array($fileExt, $allowedExts)){ // 仅连接一次数据库 $connection = mysqli_connect($apews_db_apews2, $apews_db_usr, $apews_db_pwd) or die ("Unable to connect!"); // 拼接refno到文件名前缀 $dest = $dataDir . $refno . $file_name; if(move_uploaded_file($file, $dest)) { echo "<script language='javascript'>alert('Visual Defect Report and pictures are successfully submitted!');</script>"; } // 关闭数据库连接 mysqli_close($connection); } else { echo "<script language='javascript'>alert('Only PNG/JPG/JPEG files are allowed!');</script>"; } } } flush(); ?>
4. 修改后的前端代码(仅调整输入框属性)
<script type="text/javascript"> const now = new Date(); let randomNum = ''; randomNum += Math.round(Math.random() * 9); randomNum += Math.round(Math.random() * 9); randomNum += now.getTime().toString().slice(-2); window.onload = function () { document.getElementById("refno").value = `${new Date().getFullYear()}${randomNum}`; } </script> <label class="control-label col-sm-4" for="refno">REF nos :</label> <div class="col-sm-4"> <p class="form-control-static" style="margin-top: -6px;"> <input type="text" class="form-control" id="refno" name="refno" value="<?php echo $refno;?>" readonly> </p> </div>
关键说明
readonly替代disabled:保证refno值能随表单提交,同时限制用户修改- 文件名拼接:直接在原文件名前追加
$refno,即可生成20221234cat.png格式的文件名 - 合并后缀判断:减少重复代码,新增非法文件类型提示
- 修复数据库连接错误:原代码最后使用未定义的
$conn关闭连接,修改为正确的$connection变量
内容的提问来源于stack exchange,提问作者Travis Sloap
相关产品推荐
相关产品推荐

