获取输入文件类型属性jquery

时间:2012-08-21 17:49:41

标签: php jquery

我的表单有一个输入字段,它接收一个文件,即时尝试获取文件的输入,让我们说一个图像。在此之后,我然后使用PHP然后检查文件类型并将其上传到数据库。我如何让jquery将图像文件发布到php,以便php可以执行其功能。我可以得到其他领域的attr而不是图像。

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.

}

可能不干净,但我希望有人明白这个想法

1 个答案:

答案 0 :(得分:1)

您可以在表单提交前点击上传按钮时使用以下代码。

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

或者:

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