我使用2个文件index.js,upload.php尝试通过ajax上传文件(img),如果成功追加到div uploadfile_show。 但是它不起作用,有几个问题,下面我的代码有什么建议吗?
uploadfile_show
谢谢。
upload.php 1. form enctype还需要添加吗? 2. if($_FILES)并检查$ _FILES的大小或tmp_name是否仍使用$_FILES?
form enctype
if($_FILES)
$_FILES
if($_FILES){ $filename = $_FILES['uploadfile']['name']; $filetmp = $_FILES['uploadfile']['tmp_name']; $filesize = $_FILES['uploadfile']['size']; if($filesize < 1000000){ move_uploaded_file($filetmp,'upload/tmp/'.$filename); print" upload success <img src=\"upload/tmp/$filename\"> "; } else{ } } else{ print" <div class=\"uploaddiv\"> <form enctype=\"multipart/form_data\"> <input type=\"type\" name=\"uploadfile\"> <input type=\"submit\" value=\"upload\" class=\"btn\"> </form> </div> "; } print" <div class=\"uploadfile_show\"></div> ";
index.js 3.这几行是对的吗? var uf = $('.uploaddiv form');var fd = new FormData(uf);fd.append('uploadfile', uploadfile); data: fd, 4.我错过或错了什么吗?
var uf = $('.uploaddiv form');var fd = new FormData(uf);fd.append('uploadfile', uploadfile);
data: fd,
$('.btn').click(function(){ var uf = $('.uploaddiv form'); var fd = new FormData(uf); fd.append('uploadfile', uploadfile); $.ajax({ type: "POST", url: "upload.php", data: fd, processData:false, contentType: false, success: function(html){ $('.uploadfile_show').append(html); } }); });
FormData 在其构造函数中接受一个form元素而不是一个jQuery对象,同样,当您使用ajax提交表单时,您必须通过调用来阻止其默认操作(即提交) preventDefault()
FormData
preventDefault()
$('.btn').click(function(e){ e.preventDefault(); var uf = $('.uploaddiv form'); var fd = new FormData(uf[0]); $.ajax({ type: "POST", url: "upload.php", data: fd, processData:false, contentType: false, success: function(html){ $('.uploadfile_show').append(html); } }); });