html 代码
1 <form action="{pboot:form fcode=8}" method="post" id="t" enctype="multipart/form-data">2 ???<input type="file" name=‘tables_a‘ id="tables" onchange="abs()">3 ???<input type="hidden" name=‘tables‘ id=‘tables_2‘>4 ???<input type="submit" value="提交">5 </form>
项目使用的是pbootCMS 所以地址可忽略
enctype="multipart/form-data"因为设计到文件上传必须在from 表单中添加该属性
js代码
1 function abs(){ 2 ???var fileArray = document.getElementById(‘tables‘).files[0]; 3 ???var formData = new FormData(); 4 ???formData.append("fileArray", fileArray) 5 ???$.ajax({ 6 ??????url: "{pboot:httpurl}/api.php/Tables/index",//传向后台服务器文件 7 ??????type: ‘POST‘, ???//传递方法 8 ??????data: formData, ?//传递的数据 9 ??????dataType : ‘json‘, ?//传递数据的格式10 ??????async:false, //这是重要的一步,防止重复提交的 ??????????????????11 ??????cache: false, ?//设置为false,上传文件不需要缓存。12 ??????contentType: false,//设置为false,因为是构造的FormData对象,所以这里设置为false。13 ??????processData: false,//设置为false,因为data值是FormData对象,不需要对数据做处理。14 ??????success: function (responseStr){15 ??????????if(responseStr.code != 0){16 ??????????????alert(‘上传成功‘);17 ??????????????$(‘#tables_2‘).val(‘{pboot:httpurl}‘+responseStr.data);18 ??????????}else{19 ??????????????alert(‘上传失败‘);20 ??????????}21 ??????},22 ??????error: function () {23 ??????????alert("上传错误!");24 ??????}25 ???});26 }
PHP代码
1 public function index() 2 { 3 ????$name = $_FILES[‘fileArray‘][‘name‘]; 4 ????$last = substr($name,strrpos($name,‘.‘)); 5 ????$name = date(‘YmdHis‘).rand(10000,99999).$last; 6 ????$address = ROOT_PATH.‘/upload/‘.$name; 7 ????if(move_uploaded_file($_FILES[‘fileArray‘][‘tmp_name‘],$address)){ 8 ????????return json(1,‘/upload/‘.$name); 9 ????}else{10 ????????return json(0);11 ????}12 }
$_FILES[‘fileArray‘][‘tmp_name‘] 是文件的临时存储位置,所以直接将他移动过去就好了
转载请说明出处谢谢!!!
php+ajax ?文件上传
原文地址:https://www.cnblogs.com/CcPz/p/10168433.html