Brownman Revival
Brownman Revival

Reputation: 3850

Option to save file or not in database as blob ajax php

I am successfully saving file in database as blob from ajax request to php file. My ajax is like this

var file = $('#fileuploader')[0].files[0];
        var formData = new FormData();
        formData.append('file', file);
}
$.ajax({
            url: '../include/Addnewstudent.php',
            type: 'POST',
            dataType: "json",
            data: formData,
            processData: false, // tell jQuery not to process the data
            contentType: false, // tell jQuery not to set contentType
            success: function(data) {
                console.log(data);
               // window.location.reload(true);
            }, error: function(data) {
                alert("Error!"); // Optional
                //window.location.reload(true);
            }
        });

in my PHP i have

    $fileName = $_FILES['file']['name'];
    $fileType = $_FILES['file']['type'];
    $fileSize = $_FILES['file']['size'];
    $fileError = $_FILES['file']['error'];

where i check the file like

if ($fileError == UPLOAD_ERR_OK) {}

My question is very simple how can i make it in a way that when the i dont want to put file it is ok.Currently when i dont put anything in the input(type file) i always get error in the $fileName = $_FILES['file']['name']; saying file is undefined so i cant make an if condition as if($fileSize = $_FILES['file']['size'] > 0) or/and i cant leave the input(type file) empty because i will certainly get the undefined index for file. How can i be able to leave the input(type file) empty and dont get the error undefined index : file. Any idea is appreciated.

GOAL

The flexibility to save or not save file in database

Upvotes: 2

Views: 756

Answers (2)

Brownman Revival
Brownman Revival

Reputation: 3850

Based on Keo's answer i played with it and i came up with this

if (!empty($_FILES)) {

and now i can save and not save based on my requirements. I achievement my goal to upload and not to upload depending on what i need

Upvotes: 1

Keo
Keo

Reputation: 1153

You have to check if $_FILES['file'] exist.

if (isset($_FILES['file'])) {
    // process file
}

Upvotes: 3

Related Questions