dtkvlj5386 2012-05-14 10:00
浏览 48

如何使用JQuery异步上传文件

I want to upload a file asynchronously using jQuery - without using any PLUGIN.

JQuery is very new to me and after looking at various forums I ended up with this code :


HTML:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">


$(document).ready(function(){

    $('#myform').submit(function() {

        var fileInput = document.getElementById('file');
        var file = fileInput.files[0];
        var formData = new FormData();
        formData.append('file', file);

        $.ajax({
            type: "POST",
            url: "upload.php",
            data: formData,
            processData: false,



            contentType: 'multipart/form-data',


                beforeSend: function (x) {
                        if (x && x.overrideMimeType) {
                            x.overrideMimeType("multipart/form-data");
                        }
                },

            success:function(msg){
                    //alert( "Data Uploaded: " + msg );
                document.getElementById('display').innerHTML = msg;

                }
            });

        return false;
    });


});

</script>
</head>

<body>
<form enctype="multipart/form-data" id="myform" name="myform" method="POST">
<input name="file" type="file" id="file" name="file"/>
<input type="text" name="txtValue" value="" id="txtValue">-->
<input type="submit" value="Upload" id="button" name="button"/>

<div id="display"></div>
</form>

</body>
</html>

PHP:

<?php

$uploaddir = './uploads/';
$file = $uploaddir . basename($_FILES['file']['name']);

if (move_uploaded_file($_FILES['file']['tmp_name'], $file)) {
  $value = "success";
} 
else {
    $value = "error";
}


echo $value; 

?>

This code is not working and everytime the "display" DIV is printing "error". Please help me out.

  • 写回答

4条回答 默认 最新

  • doqw89029 2012-05-14 10:08
    关注

    Take a hidden div. Inside that div take a iframe and set the form's target to the iframe's id.

    In jQuery. In after document ready function add a load event handler (say LEH)to the iframe. So that when the form is submitted and file is uploaded and iframe is loaded then the LEH will get called

    This will act like success event.

    Note: you need to make minor tweaks as for the first time when the page is loaded then also the iframe is loaded. So there will be a first time check also.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)