PHP file upload, sending formdata object

11,862

Added to jQuery.ajax and it works now:

processData: false,

contentType: false,
Share:
11,862
Erik
Author by

Erik

Updated on August 21, 2022

Comments

  • Erik
    Erik almost 2 years

    I want to upload a file, send it to javascript formData object and than via ajax to some php script which will put the file into database. It works fine when i upload a file in profile php, send it to formData object in javascript and send it back to profile.php. Problem is that when i want to send formData object to some other php script which isn't profile.php, it doesn't work.

    Here is my code:

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

    And than I want to check in some other php (script.php) script if file was uploaded.

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