關於JS提交file 上傳文件
最近因寫一個上傳功能,不能刷新頁面,且頁面得有後臺返回的信息,因而不能使用form直接提交表單,嘗試使用is提交併接受返回數據,不多說代碼如下:
前臺:
js:
function upload(o){
var data = new FormData(document.getElementById('pdf-form'));
data.append('CustomFile','this is data');
var PDF = new XMLHttpRequest();
PDF.open("post",'<{link app=b2c ctl=site_paycenter act=uploadFile}>',true);
PDF.onload = function(){
if(PDF.status == 200){
re =JSON.decode(PDF.responseText);
console.log(re);
if( re.rsp == 'succ'){
document.getElementById('button').style.display= 'none';
document.getElementById("span").innerHTML=re.res;
document.getElementById('span').style.display= '';
// document.getElementById("url").href='.'+re.url;
}else{
document.getElementById("span").innerHTML=re.res;
document.getElementById('span').style.display= '';
}
}
};
PDF.send(data);
}
後臺處理以及返回信息:
function uploadFile()
{
$file = $_FILES['inputpdf']['name'];
$filetempname = $_FILES['inputpdf']['tmp_name'];
$filelist = explode('.',$file);
$type = end($filelist);
if($type != 'pdf'){
$return = array (
'rsp' => 'fail',
'res' => '請上傳pdf文件!',
);
echo json_encode($return);exit;
}
//自己設置的上傳文件存放路徑
$filePath = './public/pdf/';
$contract_name = $file;
$string_md5 = md5 (md5($contract_name).time());
$front_string = substr ($string_md5 ,0 ,31 );
$contract_url = 's'.$front_string.'.pdf'; //pdf名稱
$uploadfile = $filePath .$contract_url;//上傳後的文件名地址
//move_uploaded_file() 函數將上傳的文件移動到新位置。若成功,則返回 true,否則返回 false。
$result = move_uploaded_file($filetempname, $uploadfile);//假如上傳到當前目錄下
if($result == true){
$orders = app::get('b2c')->model('orders')->getList('contract_no', array('order_id'=>$_POST['order_id'])); //獲取用戶發票信息
$contracts = app::get('b2c')->model('contract_list')->getList('*', array('contract_no'=>$orders[0]['contract_no'])); //獲取用戶默認收貨地址
$contract_no = $orders[0]['contract_no'];
$delfile = $contracts[0]['contract_url'];
$contracts[0]['contract_url'] = $uploadfile;
$contracts[0]['contract_name'] = $contract_name;
$contracts[0]['uptime'] = date('Y-m-d H:i:s',time());
// unset($contracts[0]['id']);
$flag = app::get('b2c')->model('contract_list')->update($contracts[0],array('id'=> $contracts[0]['id']));
if($flag){
if(file_exists($delfile)){
unlink($delfile);
}
$return = array (
'rsp' => 'succ',
'url' => "/paycenter-download-$contract_no.html",
'res' => '上傳成功!',
);
echo json_encode($return);exit;
}
}else{
$return = array (
'rsp' => 'fail',
'res' => '上傳失敗!',
);
echo json_encode($return);exit;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.