1

Hello and good day everyone! I am here to ask on how to pass a file type using javascript, so that I can use it to another php page. The following is an input for type file:

<input type="file" name="imgCompany" id="imgCompany">

I am getting the file like this in php:

$file = $_FILES['imgCompany']['tmp_name'];

The first question I have to ask is how can I get the $file variable to be place in a javascript function? (same php page). So far this was my attempt to do so:

function addImage() {
  var companyImage = $('#imgCompany').val();
}

The second question I have to ask how do I pass that file value once it is declared in the addImage() function using a method like this:

$.post('addImage.php', {postimage:file},
function(data)
{
    //returns the echoed value from the php file
    $('#result').html(data);
});

Or is there another way?

I am going to use what I pass from the post to another php page, so I can upload that image into a database. I am uploading this image into a database like this:

    ...
    $image = addslashes (file_get_contents($_FILES['image']['tmp_name']));
    //$image_name = addslashes ($_FILES['image']['name']);
    $image_size = getimagesize($_FILES['image']['tmp_name']);

    if ($image_size == FALSE)
        echo "<h3 class='warningStyle' align='center' style='position:absolute; top:235px; left:660px;'>No Image was Selected</h3>";
    else {

        if (!$insert = $db->query ("INSERT INTO company VALUES('','$companyName','$image')"))
            echo "<h3 class='warningStyle' align='center' style='position:absolute; top:235px; left:650px;'>Problem uploading the image</h3>";
    else {
        echo "<h3 class='successStyle' align='center' style='position:absolute; top:235px; left:620px;'>Company Account successfully created</h3>";
    }

}
ROOT
  • 11,363
  • 5
  • 30
  • 45
paopao33
  • 107
  • 4
  • 13

1 Answers1

0

I cannot read JQuery (nor do I want to), but here are a few pointers:

The file name in file-upload: javascript-how-to-extract-filename-from-a-file-input-control

The second question I have to ask how do I pass that file value once it is declared in the addImage() function using a method like this:

You don't have to, the file will be send in the form you are sending. I do not understand what you are trying to accomplish by adding javascript to that. The original filename will also be send to the server. (Inspect the $_FILES on arrival to see it for yourself)

About the insertion in the database:

addslashes? Really? Escape it in another way, preferable with the quotation/escape functionality delivered with your database.

And another thing: If you go to "another page" your $_FILES will be empty. Handle it on arrival, not after invoking a new page. I am not sure what or how you are doing it, but keep that in mind when you see an empty $_FILES while you expected some information in it. :-)

Community
  • 1
  • 1
Erwin Moller
  • 2,375
  • 14
  • 22