0

I am trying to do a simple pdf/excel file upload by storing the file into an upload folder and saving the name into the database. The problem here is that after i click on the upload button, the database saves my $transaction->test = "something"; but not the file or directory.

<input type="file" id="upload" name="upload" accept="application/pdf,application/vnd.ms-excel" />
<input id="next" class="btn btn-primary" type="button" value="Upload" />

<script>
uploadFile : function (upload) {
           $.ajax({
                type: 'POST',
                url: 'upload.php',
                data: { 
                upload: $('#upload').val(),
                },
               success: function(data)
                {
                    if(data.result == true){
                        alert("File has been uploaded successfully");
                    }   
                    else{
                    alert("Fail to upload file");
                    }       
                },
            });
                return false;
}
</script>

upload.php

public function uploadFile($params){
    extract($params);
    $response = $this->response;
    $agentId = $this->getCurrentId();
    
    $agent    = Investor::fetch($agentId); //fetching user info
    if(count($POST)>0){
        $d=(object)$POST;
        $transaction = new Transaction (); //create new data
        $transaction->test = "something"; //this works
        $target_dir = "../uploads/";
        $target_file = $target_dir . basename($_FILES["upload"]["name"]);
        $fileUpload = move_uploaded_file($_FILES['upload']['tmp_name'], $target_file);       
         if($fileUpload){
             $transaction ->description = $fileUpload;
             $transaction->save ();
             $this->success();
             $this->response['result'] = true;       
         }
         else{
            $this->response['result'] = false;
         }
        }
    return $this->response;
 }

2 Answers 2

2

The jquery ajax you are using will not upload the file. You have to make FormData and append the file in it like:

$('#upload').on('click', function() {
        var file_data = $('#pic').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);

        $.ajax({
                url         : 'upload.php',     // point to server-side PHP script 
                dataType    : 'text',           // what to expect back from the PHP script, if anything
                cache       : false,
                contentType : false,
                processData : false,
                data        : form_data,                         
                type        : 'post',
                success     : function(output){
                    alert(output);              // display response from the PHP script, if any
                }
         });
         $('#pic').val('');                     /* Clear the file container */
    });

upload.php:

if ( $_FILES['file']['error'] > 0 ){
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
        {
            echo "File Uploaded Successfully";
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

may i ask what does $('#pic').prop('files')[0] do and how do i retrieve the #pic value?
here $('#pic') is the id of input type image and the whole line returns File { name="450726.png", lastModified=1489048084000, lastModifiedDate=Date, more...} the file object
0
<!DOCTYPE html>
<html>
<head>
    <title>Image Upload Form</title>
    <script src="//code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        function submitForm() {
            console.log("submit event");
            var fd = new FormData(document.getElementById("fileinfo"));
            fd.append("label", "WEBUPLOAD");
            $.ajax({
              url: "upload.php",
              type: "POST",
              data: fd,
              processData: false,  // tell jQuery not to process the data
              contentType: false   // tell jQuery not to set contentType
            }).done(function( data ) {
                console.log("PHP Output:");
                console.log( data );
            });
            return false;
        }
    </script>
</head>

<body>
    <form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
        <label>Select a file:</label><br>
        <input type="file" name="file" required />
        <input type="submit" value="Upload" />
    </form>
    <div id="output"></div>
</body>
</html>

//upload.php
<?php
if ($_POST["label"]) {
    $label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    } else {
        $filename = $label.$_FILES["file"]["name"];
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

        if (file_exists("uploads/" . $filename)) {
            echo $filename . " already exists. ";
        } else {
            move_uploaded_file($_FILES["file"]["tmp_name"],
            "uploads/" . $filename);
            echo "Stored in: " . "uploads/" . $filename;
        }
    }
} else {
    echo "Invalid file";
}
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.