如何使用 JQuery 异步上传文件


how to Upload file asynchronously using JQuery

我想使用 jQuery 异步上传文件 - 不使用任何插件。

JQuery 对我来说很新,在查看了各种论坛后,我最终得到了这段代码:


.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; 
?>

此代码不起作用,每次"显示"DIV 打印"错误"时。请帮帮我。

取一个隐藏的div。 在该div 中,取一个iframe并将表单的target设置为 iframe 的 id。

在jQuery中。在文档就绪后函数中,将加载事件处理程序(例如 LEH)添加到 iframe。这样,当提交表单并上传文件并加载 iframe 时,LEH 将被调用

这将像成功事件一样。

注意:您需要进行细微调整,因为第一次加载页面时也会加载iframe。所以也会有第一次检查。

使用 HTML5,您可以使用 Ajax 和 jQuery 进行文件上传。不仅如此,您还可以执行文件验证(名称、大小和 MIME 类型)或使用 HTML5 进度标记(或div)处理进度事件。

该 HTML:

<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>
<progress></progress>

如果需要,可以进行一些验证。

$(':file').change(function(){
    var file = this.files[0];
    var name = file.name;
    var size = file.size;
    var type = file.type;
    //Your validation
});

现在,Ajax 通过单击按钮提交:

$(':button').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: 'upload.php',  //Server script to process data
        type: 'POST',
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // Check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
            }
            return myXhr;
        },
        //Ajax events
        beforeSend: beforeSendHandler,
        success: completeHandler,
        error: errorHandler,
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
});

现在,如果您想处理进度。

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}

您可以使用以下插件使用 ajax 上传文件:

  1. j查询表单插件

  2. 上传

第一个链接中的插件提供了一些非常有用的回调。您可以在给定的链接中查看文档。

我的项目中有用户Jquery Form插件。JQuery 原始 xhr 对象被包装在 jqXhr 对象中,该对象没有任何对 xhr 的新上传属性的引用。希望您可以从以下示例开始。.html:

 <input type="file" class="text-input" size="50" id="file_upload" value=""  name="file_upload"/>
var formData = new FormData($('form')[0]);
$.ajax({
url: '/files/add_file',  //server script to process data
type: 'POST',
xhr: function() {  // custom xhr
 myXhr = $.ajaxSettings.xhr();
 if(myXhr.upload){ // check if upload property exists
    //myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
dataType: 'JSON',
beforeSend: beforeSendHandler,
success: function(data) {
    if (data.error){
       showMessage(data.html, false, false);
        }
    else{
       showMessage(data.html, false, false);
setTimeout("window.location = 'path/to/after/uploading';",450)
}
},
error: function(data) {
    showMessage(data.html, false, false);
},
// Form data
data: formData,
   //Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});