2010-04-07 66 views
14

目前我想实现图片上传而不使用任何插件。使用jQuery的ajax方法(无插件)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> 

我的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; 
     }); 

如果我打开萤火虫,我可以看到,阿贾克斯()方法简单的表格后(不是多 - 部分)和POST内容为空

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

非常感谢你

回答

13

jQuery的AJAX不支持文件上传和执行这一手动可能很麻烦。我建议你看看jQuery form插件。

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

下面是一个例子你的代码可能看起来怎么样:

$(function() { 
    $('#uploadform').ajaxForm(); 
}); 

也使上传按钮提交按钮:

<button class="btn-bl" id="upComplete" type="submit"> 
    <span>Upload</span> 
</button> 
+0

接缝合理,会试试jquery表单插件,谢谢:) – 2010-04-07 09:40:24

7

AJAX或更合适XMLHttpRequest尚不支持文件上传。有一些解决方法,例如通过上传,但其相当麻烦。您的时间将会更好地用于构建应用程序,而不是重新创建这些解决方案。

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

基本上,你改变了形式target提交内,从而避免了页面刷新,并模拟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(); 
});​​​​​​ 

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

3

虽然您可以自己创建一个multipart/form-data请求正文以包含文件上传字段,但它不会帮助您,因为您无法从文件上载字段读取客户端文件。

(除了使用FileList接口,但目前只有Firefox支持。)

+0

对'FileList' +1。关于通过将文件拖放到窗口来处理时间文件上传。 – Anurag 2010-04-07 10:20:59

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; 
} 

用于将文件复制在服务器端,如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); 

这是一个简单的想法,例如不完整的工作脚本。希望这可以帮助。欲了解更多信息请参考https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest

0
<input type="file" id="picfile" name="picf" /> 
     <input type="text" id="txtName" style="width: 144px;" /> 
    <input type="button" value=" ADD " id="btncatsave" style="width: 75px" /> 
$("#btncatsave").click(function() { 
var Name = $("#txtName").val(); 
var formData = new FormData(); 
var totalFiles = document.getElementById("picfile").files.length; 

        var file = document.getElementById("picfile").files[0]; 
        formData.append("FileUpload", file); 
        formData.append("Name", Name); 

$.ajax({ 
        type: "POST", 
        url: '/Category_Subcategory/Save_Category', 
        data: formData, 
        dataType: 'json', 
        contentType: false, 
        processData: false, 
        success: function (msg) { 

           alert(msg); 

        }, 
        error: function (error) { 
         alert("errror"); 
        } 
       }); 

}); 

[HttpPost] 
    public ActionResult Save_Category() 
    { 
     string Name=Request.Form[1]; 
     if (Request.Files.Count > 0) 
     { 
      HttpPostedFileBase file = Request.Files[0]; 
     } 


    }