首页 > jQuery+ajax文件上传失败,什么原因?

jQuery+ajax文件上传失败,什么原因?

html部分:

<h2>文件上传</h2>
        <form id="up">
        <input type="file" name="pic" class="pic" />
        <input type="button" value="提交" class="sub" />
     </form>

后端php部分:ajax.php

<?php 
header("Content-Type: text/html;charset=utf8");


move_uploaded_file($_FILES["pic"]["tmp_name"],
"./" . "www.png");

?>

js部分,用js上传的时候是成功的,但用jquery的时候出现了两种错误:
一种是用$.ajax方法:

$(function(){
        $(".sub").click(function(){
    
         var fd=new FormData($("#up"));
             
       $.ajax({  
          url: 'ajax.php' ,  
          type: 'POST',  
          data: fd,  
          async: false,  
          cache: false,  
          contentType: false, 
          processData: false,  
          success: function (returndata) {  
              alert(returndata);  
          },  
          error: function (returndata) {  
              alert(returndata);  
          }  
     });  
            
})
})  

报错说找不到$_FILES里的pic,为什么呢?
补充:这个地方搞定了,var fd=new FormData($("#up"));需要写成:
var fd=new FormData($("#up")[0]);
具体可见:http://.com/q/1010000004213457
和 http://.com/a/1190000002938709

用$.post方法的时候:

$.post("ajax.php",fd,function(data){
            console.log(data);
         })

报错:Uncaught TypeError: Illegal invocation
这又是为什么呢?
(jquery是1.7.1版本的)


可参考我写的关于FormData不刷新上传文件

FormData


ajax只能传输文本流,不能运输二进制的文件。


ajax不能上传文件,还有form上传文件的enctype属性是要有的


Ajax是不能上传附件的,如果需要上传附件请参考使用jQuery form插件


      contentType: false, 
      processData: false,

设置不对。

var data = new FormData();
data.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
        url: 'ajax.php',
        data: data,
        processData: false,
        type: 'POST'
        contentType: 'multipart/form-data',
        mimeType: 'multipart/form-data',
        success: function (data) {
            alert(data);
        }
    });
【热门文章】
【热门文章】