如何在ajax调用中传递input type file数据

3

我有我的表单

<form name="photo" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
    Photo <input type="file" name="image" size="30" />
          <input type="submit" name="upload" value="Upload" />
</form>

以下代码用于通过调用self(同一文件)上传图像(代码来自http://www.webmotionuk.co.uk/php-jquery-image-upload-and-crop-v11/
if (isset($_POST["upload"])) { 
    //Get the file information
    $userfile_name = $_FILES['image']['name'];
    $userfile_tmp = $_FILES['image']['tmp_name'];
    $userfile_size = $_FILES['image']['size'];
    $userfile_type = $_FILES['image']['type'];
    $filename = basename($_FILES['image']['name']);
    $file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

    //Only process if the file is a JPG, PNG or GIF and below the allowed limit
    if((!empty($_FILES["image"])) && ($_FILES['image']['error'] == 0)) {

        foreach ($allowed_image_types as $mime_type => $ext) {
            //loop through the specified image types and if they match the extension then break out
            //everything is ok so go and check file size
            if($file_ext==$ext && $userfile_type==$mime_type){
                $error = "";
                break;
            }else{
                $error = "Only <strong>".$image_ext."</strong> images accepted for upload<br />";
            }
        }
        //check if the file size is above the allowed limit
        if ($userfile_size > ($max_file*1048576)) {
            $error.= "Images must be under ".$max_file."MB in size";
        }

    }else{
        $error= "Select an image for upload";
    }
    //Everything is ok, so we can upload the image.
    if (strlen($error)==0){

        if (isset($_FILES['image']['name'])){
            //this file could now has an unknown file extension (we hope it's one of the ones set above!)
            $large_image_location = $large_image_location.".".$file_ext;
            $thumb_image_location = $thumb_image_location.".".$file_ext;

            //put the file ext in the session so we know what file to look for once its uploaded
            $_SESSION['user_file_ext']=".".$file_ext;

            move_uploaded_file($userfile_tmp, $large_image_location);
            chmod($large_image_location, 0777);

            $width = getWidth($large_image_location);
            $height = getHeight($large_image_location);
            //Scale the image if it is greater than the width set above
            if ($width > $max_width){
                $scale = $max_width/$width;
                $uploaded = resizeImage($large_image_location,$width,$height,$scale);
            }else{
                $scale = 1;
                $uploaded = resizeImage($large_image_location,$width,$height,$scale);
            }
            //Delete the thumbnail file so the user can create a new one
            if (file_exists($thumb_image_location)) {
                unlink($thumb_image_location);
            }
        }
        //Refresh the page to show the new uploaded image
        header("location:".$_SERVER["PHP_SELF"]);
        exit();
    }
}

现在我想使用ajax来实现这个。我如何将文件数据传递到处理文件中,以便我可以使用类似于以下内容的东西?
$('#uploadBtn').live('click', function(){
        var data = "upload=true";
        $.ajax({
            type: "POST",
            url: "process.php",
            data: data,
            cache: false,
            success: function(data){
            }
        });
    });
3个回答

14

我用Firefox和Chrome尝试过类似以下的方法:

<form id="guestForm" action="<?php echo $_SERVER["PHP_SELF"];?>" method="POST" enctype="multipart/form-data">
   <input type="file" id="fileInput" name="fileInput" />
   <input type="button" value="submit" id="ajaxSubmit" />
</form>
<script type="text/javascript">
    $(function () {
        $("#ajaxSubmit").click( function () {
            var fd = new FormData();

            fd.append( "fileInput", $("#fileInput")[0].files[0]);
            $.ajax({
                url: 'process.php',
                type: 'POST',
                cache: false,
                data: fd,
                processData: false,
                contentType: false,
                beforeSend: function () {
                    $("#output").html("Uploading, please wait....");
                },
                success: function () { 
                    $("#output").html("Upload success.");
                },
                complete: function () {
                    $("#output").html("upload complete.");
                },
                error: function () {
                    alert("ERROR in upload");
                }
            });

        });
    });
</scirpt>

我最初将此代码与Java配合作为服务器端代码。虽然我不知道为什么这不能与PHP一起使用。但是,您的问题是如何在ajax调用中传递input type file数据。所以这就是我是如何做的。


1
注意,FormData在更高版本的浏览器中支持,如IE 10及以上版本。因此,这段代码不适用于使用老旧浏览器的人。请参见:https://developer.mozilla.org/en-US/docs/Web/API/FormData?redirectlocale=en-US&redirectslug=Web%2FAPI%2FXMLHttpRequest%2FFormData#Browser_compatibility - Phil
我知道这是一个比较老的问题,但是这个服务器端的代码长什么样子呢? - WWZee

1

试试这个:

$.ajax( {
  type: 'POST',
  url: 'process.php',
  data: new FormData( this ),
  processData: false,
  contentType: false,
  cache: false,
  success: function(data){
  }
});

-13

这是不可能的。

通过ajax调用发送数据不受浏览器支持。

可接受的解决方法是在后台通过隐藏的iframe提交文件(看起来像ajax)。这里的解决方案是找到您选择的“ajax文件上传”库并使用它来上传文件。


8
请查看JavaScript中的XHR2对象,这并不是真的。它完全支持它。 - Eric Hodonsky
这在大多数现代的HTML5浏览器中都是可能的。Iframe的解决方法只有在需要支持IE8一代浏览器时才会用到。 - DalSoft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接