0

i have a form that has an input field that takes in a file, im trying to get the input of a file, lets say an image. after this i then use php to then check the file type and upload it to a database. how can i get jquery to post the image file to php so that php can perform its function. i can get the attr of other fields but not the image.

html

<input type="file" name="upload" id="upload"/>

jquery

//how do get the file
var img = //left blank what should i get
var a = 'form1';
var url = "upload_data.php";
$.post(url, {a:a, file:img, other:fields}){
//success
}

php

$p = $_POST['a'];
$file = $_POST['file'];

$iname = $_FILES['file']['name'];

$isize= $_FILES['file']['size'];

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

$otherfield = $_POST['other'];
if($p = 'form1'){

form1func($otherfield, $file, $iname, $itemp); // at this point will this work since i used jquery if wont what is the best solution at this point.

}

may not be clean but i hope someone gets the idea

2
  • You cannot do this with jQuery's post. You'll have to either use flash, or do it from within an iframe. There are many libraries out there that can do this for you. Here's one: valums.com/ajax-upload Commented Aug 21, 2012 at 17:53
  • In case you want to upload the file using ajax here, well, that's not possible (only with IFrames). However, it should be possible to access the file's value attribute to check the file name string using $('input[type=file][name=whatever]').val(); . Commented Aug 21, 2012 at 17:54

1 Answer 1

1

You can use following code on upload button click before form submit.

var ext = $('#upload').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
    alert('invalid extension!');
}

Or :

var filename = jQUery('#upload').val().trim();
var valid_extensions = /(\.jpg|\.jpeg|\.gif|\.png|\.bmp)$/i;   
if(valid_extensions.test(filename))
{ 
   alert('OK');
}
else
{
   alert('Invalid File');
}
Sign up to request clarification or add additional context in comments.

1 Comment

this is useful, although it didn't answer the question. thanks thou

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.