关于JS提交file 上传文件
最近因写一个上传功能,不能刷新页面,且页面得有后台返回的信息,因而不能使用form直接提交表单,尝试使用is提交并接受返回数据,不多说代码如下:前台:<formid='pdf-form'enctype="multipart/form-data"method="POST"action=""><inputtype="hidden"name="order_id"value="<{$order.order_id}>"><tablealign="center"width="90%"border="0"><tr><td><b>合同信息:</b><atarget="_self"href="<{linkapp=b2cctl=site_paycenteract=downloadarg0=$contract_no}>"class="active">下载</a></td><{if$sign==1}><td><inputtype="file"name="inputpdf"id="inputpdf"><{buttonid="button"onclick="upload(this);"class="btn-import"label="合同上传"}><spanid="span"class="successnotice-inline">上传成功!</span></td><{/if}></tr></table></form>js:functionupload(o){vardata=newFormData(document.getElementById('pdf-form'));data.append('CustomFile','thisisdata');varPDF=newXMLHttpRequest();PDF.open("post",'<{linkapp=b2cctl=site_paycenteract=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);}后台处理以及返回信息:functionuploadFile(){$file=$_FILES['inputpdf']['name'];$filetempname=$_FILES['inputpdf']['tmp_name'];$filelist=explode('.',$file);$type=end($filelist);if($type!='pdf'){$return=array('rsp'=>'fail','res'=>'请上传pdf文件!',);echojson_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-dH: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'=>'上传成功!',);echojson_encode($return);exit;}}else{$return=array('rsp'=>'fail','res'=>'上传失败!',);echojson_encode($return);exit;}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。