前台html与后台php通信(上传文件)

这部分为导入txt文本文件,存放在服务器然后返回txt文本的内容到前台进行相应操作
前台html代码
<div id="coordinate_div">
       <div class="file-box">
           <form action="" method="post" enctype="multipart/form-data">
               <input type='text' name='textfield' id='textfield' class='txt' />
               <input type='button' class='btn' value='浏览...' />
               <input type="file" name="fileField" class="file" id="fileField" size="28" onchange="document.getElementById('textfield').value=this.value" />
               <input type="submit" name="submit" class="btn" value="导入" id="input" />
           </form>
         </div>
       </div>
</div>
javascript部分函数完成于后台的交互
 //后台导入文件读取内容
    $("#input").click(function() {
        var arrjson = new Array();//接收数据
        var url ="http://localhost:8081/hangshe/index.php?option=com_nasm_functiondb&task=getTxtData";//地址
        //回调函数以及返回值
        var callback = function(json){
            arrjson = json//接收这个数据
        }
        $.post(url,callback)//Ajax的post方法(url为后台php函数的调用路径,callback即获取后台返回的数据函数,还有其他参数此处为用到不再过多解释)
    });
 
 
//后台php函数
 function getTxtData()
    {
        //$txt_path = $this->getPath();//路径
        $txt_path = "D:Program Files (x86)Apache Software FoundationApache2.2htdocshangsheuploadgetname.txt";//路径
        $handle = fopen ($txt_path, "rb");//打开文件
        $contents = "";//定义变量
        while (!feof($handle)) {
            $contents .= fread($handle, 1024);//读取
        }
        //echo($contents );//输出
        fclose($handle);//关闭
        $data = explode("|","$contents");//分割为数组
        header('Content-Type:application/json; charset=utf-8');
        echo json_encode($data);//输出
        return json_encode($data);//返回为json
    }
//存储文件的函数
 function getPath(){
        //文件存储路径
        $file_path="upload/";
        //664权限为文件属主和属组用户可读和写,其他用户只读。
        if(is_dir($file_path)!=TRUE) mkdir($file_path,0664) ;
        //定义允许上传的文件扩展名
        $ext_arr = array("txt", "xlsx", "shp");
 
        if (empty($_FILES) === false) {
 
            if($_FILES["file"]["error"] > 0){
                exit("文件上传发生错误:".$_FILES["fileField"]["error"]);
            }
 
            //获得文件扩展名
            $temp_arr = explode(".", $_FILES["fileField"]["name"]);
            $file_ext = array_pop($temp_arr);
            $file_ext = trim($file_ext);
            $file_ext = strtolower($file_ext);
            //检查扩展名
            if (in_array($file_ext, $ext_arr) === false) {
                exit("上传文件扩展名是不允许的扩展名。");
            }
            //重命名文件 以时间戳重命名文件
            $new_name = time().".".$file_ext;
            //将文件移动到存储目录下
            move_uploaded_file($_FILES["fileField"]["tmp_name"],"$file_path" . $new_name);
            return "upload/"+$new_name;
        } else {
            echo "无正确的文件上传";
            return;
        }
    }
原文地址:https://www.cnblogs.com/duoduo0605/p/3388099.html