PHP文件上传,发送formdata对象

时间:2013-10-30 17:38:13

标签: javascript php mysql ajax

我想上传一个文件,将其发送到javascript formData对象,然后通过ajax发送到一些将脚本放入数据库的php脚本。当我在配置文件php中上传文件,将其发送到javascript中的formData对象并将其发送回profile.php时,它工作正常。问题是当我想将formData对象发送到一些不是profile.php的其他php脚本时,它不起作用。

这是我的代码:

profile.php

<form role="form" id="editUserProfile" method="post" action="" enctype="multipart/form-data">
    <input type="file" id="filename" name="filename" class="file-input" accept="image/*"/></a>
    <button type="submit">Save</button
</form>

javascript.js

    $('#editUserProfile').validate({
        submitHandler: function (form) {
            var aFormData = new FormData();

            aFormData.append("filename", $('#filename').get(0).files[0]);

            $.ajax({
                type: "POST",
                url: "script.php",
                data: aFormData,
                success: function(data){
                    window.location.reload(true);
                }
            })
        }
    });

如果文件已上传,我想查看其他一些php(script.php)脚本。

if(is_uploaded_file($_FILES['filename']['tmp_name']) && getimagesize($_FILES['filename']['tmp_name']) != false){
    $size = getimagesize($_FILES['filename']['tmp_name']);
    $type = $size['mime'];
    $imgfp = fopen($_FILES['filename']['tmp_name'], 'rb');
    $size = $size[3];
    $name = $_FILES['filename']['name'];
    $maxsize = 99999999;

    if($_FILES['userfile']['size'] < $maxsize ){
        $dbh = new PDO("mysql:host=localhost;dbname=test", 'root');
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $dbh->prepare("INSERT INTO table (image_type ,image, image_size, image_name) VALUES (? ,?, ?, ?)");

        $stmt->bindParam(1, $type);
        $stmt->bindParam(2, $imgfp, PDO::PARAM_LOB);
        $stmt->bindParam(3, $size);
        $stmt->bindParam(4, $name);

        $stmt->execute();
    }else{
        throw new Exception("File Size Error");
    }
}

1 个答案:

答案 0 :(得分:5)

已添加到jQuery.ajax,现在可以使用了:

processData: false,

contentType: false,