如何在服务器端检查文件格式

时间:2012-02-08 00:48:37

标签: php jquery

var $imagefile = $('<input />')
    .attr({
        type: 'file',
        name: 'imageFile',
        id: 'imageFile'
    });

以上是我创建文件输入的代码。

下面是检查表格行中文件格式是否正确的代码:

function validation() {

    var marks = parseInt($("#total-weight").text());    
    var _qid = "";
    var _msg = "";


    var allowedTypes = ["jpg", "jpeg", "gif", "png"];

    var path = $("#imageFile").val();
    var ext = path.substring(path.lastIndexOf('.') + 1).toLowerCase();


    var alertValidation = "";
    // Note, this is just so it's declared...
    $("tr.optionAndAnswer").each(function() {


        _qid = $("td.qid",this).text();
        _msg = "You have errors on Question Number: " + _qid + "\n";


         $("#imageFile",this).each(function() {

        if ($.inArray(ext, allowedTypes) < 0) {
        alertValidation += '\n\u2022 Unsupported file type';
        }

         if (alertValidation != "") {
                return false; //Stop the each loop 
            }

    });

        if(alertValidation != ""){
            return false;
        }
    });


    if (alertValidation != "") {
        alert(_msg + alertValidation);
        return false;
    }

    return true;
}

现在检查客户端的文件格式,但是如何使用php在服务器端检查?

3 个答案:

答案 0 :(得分:2)

试试这段代码。

<?php
$allowedImageTypes = array("image/pjpeg","image/jpeg","image/jpg","image/png","image/x-png","image/gif");
$file = $_FILES['imageFile'];
$fileType = $file['type'];
if (!in_array($fileType, $allowedImageTypes)) { 
    echo "Unsupported file type";
}
else
{
    // Process the file
}
?>

修改

由于用户询问了检查服务器文件的方法。他可以用这种方式来检查。

<?php

$filePath = "image/image.jpg";
list($width, $height, $type, $attr) = getimagesize($filePath);
$fileType = image_type_to_mime_type($type);
$allowedImageTypes = array("image/pjpeg","image/jpeg","image/jpg","image/png","image/x-png","image/gif");
if (!in_array($fileType, $allowedImageTypes)) { 
    echo "Unsupported file type";
}
else
{
    // Process the file
}

?>

答案 1 :(得分:0)

上传文件后,您只需查看$_FILES['imageFile']['type']即可获取mime类型。

答案 2 :(得分:0)

我会使用PHP的finfo_file函数:

http://www.php.net/manual/en/function.finfo-file.php

php页面示例:

<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
    echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);

输出:

text / html的
图像/ GIF
应用/ vnd.ms-Excel中