2014-01-08 52 views
0

我在线上关注了一个非常有用的教程,通过AJAX在HTML表单中上传文件。 下面是我的HTML代码,然后是jQuery代码。PHP中的Ajax XHR2文件上传访问值

HTML

<input type="file" id="myFile" name="myFile" /> 
<input type="button" id="upload" value="upload" /> 
<br /> 
<progress id="prog" value="0" min="0" max="100"></progress> 

jQuery的

$("#upload").on("click",function() { 
    $("#myFile").upload("xhr2.php", function(success) { 
    },$("#prog")); 
}); 

我如何可以访问PHP上传的文件来处理数据,并输出到页面的任何错误?

编辑

// data is optional 
    $.fn.upload = function(remote,data,successFn,progressFn) { 
     // if we dont have post data, move it along 
     if(typeof data != "object") { 
      progressFn = successFn; 
      successFn = data; 
     } 
     return this.each(function() { 
      if($(this)[0].files[0]) { 
       var formData = new FormData(); 
       formData.append($(this).attr("name"), $(this)[0].files[0]); 

       // if we have post data too 
       if(typeof data == "object") { 
        for(var i in data) { 
         formData.append(i,data[i]); 
        } 
       } 

       // do the ajax request 
       $.ajax({ 
        url: remote, 
        type: 'POST', 
        xhr: function() { 
         myXhr = $.ajaxSettings.xhr(); 
         if(myXhr.upload && progressFn){ 
          myXhr.upload.addEventListener('progress',function(prog) { 
           var value = ~~((prog.loaded/prog.total) * 100); 

           // if we passed a progress function 
           if(progressFn && typeof progressFn == "function") { 
            progressFn(prog,value); 

           // if we passed a progress element 
           } else if (progressFn) { 
            $(progressFn).val(value); 
           } 
          }, false); 
         } 
         return myXhr; 
        }, 
        data: formData, 
        dataType: "json", 
        cache: false, 
        contentType: false, 
        processData: false, 
        complete : function(res) { 
         var json; 
         try { 
          json = JSON.parse(res.responseText); 
         } catch(e) { 
          json = res.responseText; 
         } 
         if(successFn) successFn(json); 
        } 
       }); 
      } 
     }); 
    }; 
+0

由于我们不知道'upload'方法是什么(它不是核心jQuery),这很难说。 – Quentin

+0

我将添加“上传”功能代码 – user3170837

+1

,可能是$ _FILES。 –

回答

0

这将是一个艰难的工作要做,因为你的形式上传,文件上传在不同的要求正在发生。这就是说你可以引用你的文件的唯一方法是让它在之前上传表单数据。有不同的方式可以引用你的文件,通过会话,将它作为额外的queryString参数传递给你的表单,使用数据库(这将是无聊的),这真的取决于你。主要的问题是它们在不同的请求中,你需要建立它们之间的连接。祝你好运!