ajax非同步上傳檔案以及匯入excle檔案到資料庫
阿新 • • 發佈:2018-11-06
html程式碼:
<div class="sc_btn_box"> <input type="file" class="sc_btn" id="file"> <span class="file_uploader">選擇</span> </div> <div class="m_img_holder"></div> <div id="show_msg" style="margin-left:80px;"></div> <div class="xz_btn"> <div class="btn btn-success queding" id="submit">確定</div> <div class="btn btn-success quxiao">取消</div> </div>
JS程式碼:
$(function () { $("#submit").click(function () { if ($("#file").val().length > 0) { ajax_upload(); }else { alert("請選擇檔案"); } }) }) function ajax_upload(){ var formData = new FormData(); formData.append('file', $('#file')[0].files[0]); $.ajax({ url:"http://127.0.0.1/newsys/upload.php?action=upload_file", type:"post", data:formData, processData:false, contentType:false, success:function(data){ alert(data); $('.tc_box').hide(); }, error:function(e){ alert("錯誤!!"); } }); }
後臺程式碼php,用$_FILES來獲取檔案的資訊,和其他上傳方式一樣
function upload_file() { $username = $_POST['username']; $account = $_POST['account']; $upload_type = $_POST['upload_type']; $dir = './upload_file/'; $pic_name = $_FILES['file']['name']; $pic_name_arr = explode('.', $_FILES['file']['name']); $suffix_str = '.' . $pic_name_arr[count($pic_name_arr)-1]; $upfile = str_replace($suffix_str, '_' . date('Y-m-d H:i:s',time()) . $suffix_str, $pic_name); $upfile = $dir . $upfile; if ($_FILES['file']['error'] > 0) { switch ($_FILES['file']['error']) { case 1: echo '檔案大小超過伺服器限制'; break; case 2: echo '檔案太大!'; break; case 3: echo '檔案只加載了一部分!'; break; case 4: echo '檔案載入失敗!'; break; } exit; } if ($_FILES['file']['size'] > 2000000) { echo '檔案過大,不能超過2M!'; exit; } if (is_uploaded_file($_FILES['file']['tmp_name'])) { $handle = fopen($_FILES['file']['tmp_name'],"r"); $file_encoding = mb_detect_encoding($handle); if ($file_encoding != 'ASCII'){ // echo "<script type=\"text/javascript\">alert(\"檔案編碼錯誤,請重新上傳!\"); </script>"; echo "檔案編碼錯誤,請重新上傳"; exit; } if (!move_uploaded_file($_FILES['file']['tmp_name'], $upfile)) { echo '上傳檔案失敗!'; exit; } // if ($suffix_str == '.csv') { // file_to_db_csv($upfile,$username,$account,$upload_type); // } else { file_to_db($upfile,$username,$account,1); // } } else { echo '上傳檔案錯誤!'; exit; } closedir($dir); // } else { // echo "已存在資料檔案!"; // } }
上傳成功後,得到檔案的絕對路徑$upfile,如果是excle檔案,還可以通過file_to_db寫入到資料庫中;
function file_to_db($file_path,$username,$account,$upload_type){
include_once '../weixin/tongji/common_func/PHPExcel_1.8.0/PHPExcel.php';
include_once '../weixin/tongji/common_func/PHPExcel_1.8.0/PHPExcel/IOFactory.php';
include_once '../weixin/tongji/common_func/PHPExcel_1.8.0/PHPExcel/Shared/Date.php';
setlocale(LC_ALL, 'zh_CN.GBK');
global $_weixin_guanggao_guanzhu_num_record;
if (file_exists($file_path)) {
$objReader1 = PHPExcel_IOFactory::createReaderForFile($file_path);
$objPHPExcel1 = $objReader1->load($file_path);
$col_str = $objPHPExcel1->getSheet(0)->getHighestColumn();
$first_col=ord('A');// ASSCLL碼
$real_col=ord($col_str);// ASSCLL碼
$field_arr = array('date','num');
$real_col_count = count($field_arr)+$first_col-1;
if ($real_col > $real_col_count) {
echo "匯入失敗,檔案資料列{$real_col}超過{$type_arr[$upload_type]}所規定的列數";
exit();
}
$suc_count = 0;
$suc_id_arr = array();
$edit_id_arr = array();
$edit_count = 0;
$msg= array();
for ($i = 2; $i <= $objPHPExcel1->getSheet(0)->getHighestRow(); $i++) {
// $col_str = chr(65);// A
$add = array();
for ($jj=0; $jj < count($field_arr); $jj++) {
$field_str = $field_arr[$jj];
$add[$field_str] = iconv('utf-8', 'gbk', $objPHPExcel1->getActiveSheet()->getCell(chr(65+$jj).$i)->getValue());
}
// 把date的日期格式轉為時間戳
$add['date_timestamp'] = PHPExcel_Shared_Date::ExcelToPHP($add['date']);
$add['date'] = date("Y-m-d",$add['date_timestamp']);
$add['post_date'] = time();
if(empty($add[$field_arr[0]])){
$msg['upload_user'] = $username;
$msg['account'] = $account;
$msg['add_ids'] = implode(',', $suc_id_arr);
$msg['edit_ids'] = implode(',', $edit_id_arr);
$msg['type'] = $upload_type;
$msg['msg'] = "新增:".$suc_count.",修改:".$edit_count;
$msg['filename'] = $file_path;
$msg['post_date'] = time();
// $_wy100_weixin_ad_upload_record->add($msg);
echo "<script>alert('匯入完畢,新增:".$suc_count.",修改:".$edit_count."');";
exit();
}
$check_list = $_weixin_guanggao_guanzhu_num_record->_list(0,1, "id", "where date_timestamp = ".$add['date_timestamp']);
if (!$check_list) {
$this_id = $_weixin_guanggao_guanzhu_num_record->add($add);
$suc_count++;
$suc_id_arr[] = $this_id;
} else {
$this_id = $_weixin_guanggao_guanzhu_num_record->edit($add,$check_list[0]['id']);
$edit_count++;
$edit_id_arr[] = $check_list[0]['id'];
}
}
echo "匯入完畢,新增:".$suc_count.",修改:".$edit_count;
} else {
// echo "<script>alert('匯入失敗,不存在上傳檔案');window.location.href='http://weixin.wy100.com/tongji/tongji_admin/index.php';</script>";
echo "匯入失敗,不存在上傳檔案";
}
exit();
}