1.html
<form id='touploadimg' method="post" enctype="multipart/form-data" > <input type="file" name='file' id='attachfile'/> <input type="hidden" name='action' value='attach'/> </form>
2.js
$("#attachfile").change(function(e){ uploadFile(); })
function uploadFile() { var file = $('#attachfile').val(); if (file != '') { var filename = file.replace(/.*(\/|\\)/, ''); var fileext = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : ''; //检查文件格式 if (fileext == 'xlsx' || fileext == 'xls'|| fileext == 'doc'|| fileext == 'docx'|| fileext == 'ppt'|| fileext == 'pptx'|| fileext == 'rar'|| fileext == 'zip'|| fileext == 'pdf'|| fileext == 'txt') { var formData = new FormData($("#touploadimg")[0]); console.log(formData); $.ajax({ url: '/uploadimg.html', type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (e) { $('#attachfile').val(''); if (e.code == 1) { $("#attachfileupload").val(e.data); $("#filecontenttext").text('上传成功'); $("#filecontentimg").attr('src','/static/images/right.png'); //及时清空避免二次选择同一文件不能触发change事件 layer.open({ content: e.msg ,skin: 'msg' ,time: 2 //2秒后自动关闭 }); } else { layer.open({ content: '上传失败,请重试' ,skin: 'msg' ,time: 2 //2秒后自动关闭 }); return false; } }, error: function (json) { $('#attachfile').val(''); layer.open({ content: '网络错误,请重试' ,skin: 'msg' ,time: 2 //2秒后自动关闭 }); return false; } }); } else { layer.open({ content: '文件格式不支持' ,skin: 'msg' ,time: 2 //2秒后自动关闭 }); return false; } } }
3.php thinkphp
public function uploadimg() { $id = $this->uid; $file = request()->file('file'); $action = request()->param('action'); if ($file) { $info = $file->move(ROOT_PATH . 'public' . DS . 'upload'. DS . $action); if ($info) { return json(array('code'=>1,'data'=>$info->getSaveName(),'msg'=>'上传成功')); } else { $this->error($file->getError()); } } $this->error('文件错误,请刷新页面重试'); }
本文为看恩吧原创文章,转载无需和我联系,但请注明来自knsay.com