我想上传文件并发送到服务器而不刷新页面。
我的HTML文件中有以下行
<form id="FileUploader" enctype="multipart/form-data" >
<input type="file" name="mfile" id="mfile" style='width:100%;' onchange="uploaded()">
</form>
function uploaded()
{
alert($('form#FileUploader')[0]);
var formData=new FormData($('form#FileUploader')[0]);
//alert(formData);
$.ajax({
url: "<?php echo $_SESSION['webpage']."/upload" ?>",
type: "POST",
async: true,
dataType: "JSONP",
data : formData
})
.success (function(response){
alert(response);
})
.error (function() { alert("Error") ; }) ;
}
upload.php文件
if ($_FILES["mfile"]["error"] >0 )
{
echo "Error: " ;
}
else
{
if (file_exists("upload_email_files/" . $_FILES["mfile"]["name"]))
{
echo $_POST["file"]. " already exists. ";
}
else
{
$otp= move_uploaded_file('$_FILES["mfile"]"name"]','/../upload_templates/');
}
}
它不起作用。任何人都可以帮我这个吗? 它不会进入upload.php并给我错误的非法调用。
谢谢, 希里什
答案 0 :(得分:3)
如果是“没有刷新页面”,则可以使用隐藏的iframe。
供参考,
http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/,
http://joekuan.wordpress.com/2009/06/12/ajax-a-simplified-version-of-file-upload-form-using-iframe/
答案 1 :(得分:1)
检查一下我没有测试过它希望这会有效http://blog.new-bamboo.co.uk/2012/01/10/ridiculously-simple-ajax-uploads-with-formdata
<form id="FileUploader" enctype="multipart/form-data" >
<input type="file" name="mfile" id="mfile" style='width:100%;' onchange="uploaded()">
</form>
function uploaded()
{
alert($('form#FileUploader')[0]);
var formData=new FormData($('form#FileUploader'));//remove [0]
//alert(formData);
$.ajax({
url: "<?php echo $_SESSION['webpage']."/upload" ?>",
type: "POST",
//async: true,//Remove this line
//dataType: "JSONP",//Remove this line
data : formData
})
.success (function(response){
alert(response);
})
.error (function() { alert("Error") ; }) ;
}
答案 2 :(得分:0)
试试这个:)
<form id="FileUploader" enctype="multipart/form-data" >
<input type="file" name="mfile" id="mfile" style='width:100%;' onchange="uploaded()">
</form>
$(document).ready(function() {
$("#form-geninfo").submit(function(e)
{
e.preventDefault();
alert($('form#FileUploader')[0]);
var formData=new FormData($('form#FileUploader')[0]);
//alert(formData);
$.ajax({
url: "<?php echo $_SESSION['webpage']."/upload" ?>",
type: "POST",
async: true,
dataType: "JSONP",
data : formData
})
.success (function(response){
alert(response);
})
.error (function() { alert("Error") ; }) ;
}
});