jQuery上传文件使用jQuery的ajax方法(没有插件)

Dan*_*rik 14 ajax asp.net-mvc upload jquery

目前我想在不使用任何插件的情况下实现图片上传.

我的上传表单看起来像这样

<form action="/Member/UploadPicture" enctype="multipart/form-data" id="uploadform" method="post">
            <span>
                <div class="upload" id="imgUpl">
                    <h3>Upload profile picture</h3>
                    <div class="clear5"></div>
                    <input  type="file" name="file" id="file"  />
                    <button class="btn-bl"  id="upComplete"><span>Upload</span></button>
                </div>

            </span>
            </form>
Run Code Online (Sandbox Code Playgroud)

我的jQuery代码是:

  $('#upComplete').click(function () {
            $('#up').hide();
            $('#upRes').show();

            var form = $("#uploadform");

            $.ajax({
                type: "POST",
                url: "/Member/UploadPicture",
                data: form.serialize(),
                success: function (data) {
                    alert(data);
                }
            });

            $.fancybox.close();
            return false;
        });
Run Code Online (Sandbox Code Playgroud)

如果我打开firebug,我可以看到ajax()方法做了简单的表单post(不是多部分),POST内容为空

是否可以使用jQuery ajax()方法上传文件,还是应该以其他方式执行此操作?

非常感谢你

Dar*_*rov 13

jQuery ajax不支持文件上传,手动实现这可能很麻烦.我建议你看一下jQuery 表单插件.

当然你可以随时查看插件的源代码,看看它是如何实现的,如果你不想包含它(它使用隐藏的iFrame,因为文件不能用AJAX上传),但为什么要这样做,如果你可以使用它直接:-)

以下是您的代码可能如下所示的示例:

$(function() {
    $('#uploadform').ajaxForm();
});
Run Code Online (Sandbox Code Playgroud)

还可以使上传按钮成为提交按钮:

<button class="btn-bl" id="upComplete" type="submit">
    <span>Upload</span>
</button>
Run Code Online (Sandbox Code Playgroud)


Anu*_*rag 7

AJAX或者更合适的XMLHttpRequest是还不支持文件上传.有一些解决方法,例如通过上传<iframe>,但它相当繁琐.您的时间将更好地用于构建应用程序,而不是重新发明这些解决方案.

但是如果你对内部的工作方式感到好奇,那么请随时查看一些提供此功能的插件的源代码.可以在此链接找到一个非常简单的解释 - http://www.openjs.com/articles/ajax/ajax_file_upload/

基本上,你改变表单target以提交内部<iframe>,从而避免页面刷新,并模拟AJAX,它不是真的,但谁在乎 - 最终用户无法分辨.

基于iframe的上传的最小示例可能如下所示:

?$("#upComplete").click(function() {
    // create a dynamic iframe, or use existing one 
    var iframe = $("<iframe id='f' name='f' src=''>");
    // attach a load event to handle response/ know about completion
    iframe.load(function() { alert('complete'); });
    iframe.appendTo('body');
    // change form's target to the iframe (this is what simulates ajax)
    $('#uploadForm').attr('target', 'f');
    $('#uploadForm').submit();
});??????
Run Code Online (Sandbox Code Playgroud)

请注意,这不会执行任何响应处理,而只是将图片发送到服务器.要处理响应,必须为iframe的load事件编写回调.


alb*_*anx 6

实际上有一种方法可以使用带有Firefox> 3和Chrome的ajax(xmlhttp)上传文件,也可以在不使用表单和iframe的情况下上传多个文件.实际上我正在制作一个jQuery插件来做这个,很快我就会发布它.这是一个简单的例子:

var file=$('<input type=file />').get(0).files[0];
function asyncupload(file)
{
    var xhr = new XMLHttpRequest();    
    xhr.onreadystatechange = function() 
    {  
        if (xhr.readyState == 4) 
        {  
            if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304) 
            {  
                //alert(xhr.responseText);
            }  
        }  
    };  
    xhr.upload.onload=function(e)
    {
        $('div#axprogress').progressbar("option", "value", 100);;
    };  
    xhr.upload.onprogress=function(e) 
    {  
        if (e.lengthComputable) 
        {  
            var perc = Math.round((e.loaded * 100) / e.total);  
            $('div#axprogress').progressbar("option", "value", perc);
        }  
    };  

    xhr.open("POST", "upload.php?filename="+file.name,true);  
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.setRequestHeader("X-File-Name", encodeURIComponent(file.name));
    xhr.send(file);  
    return xhr;
}
Run Code Online (Sandbox Code Playgroud)

要获取服务器端的文件,比如php,必须为upload.php执行此操作:

$input = fopen("php://input", "r");
$temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp);
fclose($input);

if ($realSize != $this->getSize())
    {            
    return false;
}

$target = fopen($_GET['filename'], "w");        
fseek($temp, 0, SEEK_SET);
stream_copy_to_stream($temp, $target);
fclose($target); 
Run Code Online (Sandbox Code Playgroud)

这是一个简单的想法示例,而不是完整的工作脚本.希望这可以帮助.有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest