zoukankan      html  css  js  c++  java
  • php中上传图片

    这里来看看php中如何上传图片的

    先看代码check_image.php

    <html>
        <head>
            <title></title>
            <style type="text/css"></style>
        </head>
        <body>
            <form action="check_image.php" method="post" enctype="multipart/form-data">
                <table>
                    <tr>
                        <td>Your username</td>
                        <td><input type="text" name="username" /></td>
                    </tr>
                    <tr>
                        <td>Upload image*</td>
                        <td><input type="file" name="uploadfile"/></td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <small><em> * Acceptable image formats include: GIF, JPG/JPEG and PNG.</em></small>
                        </td>
                    </tr>
                    <tr>
                        <td>Image Caption</td>
                        <td><input type="text" name="caption"/></td>
                    </tr>
                    <tr>
                        <td colspan="2" style="text-align:center;">
                            <input type="submit" name="submit" value="Upload" />
                        </td>
                    </tr>
                </table>
            </form>
        </body>
    </html>

    这里没什么可以说的,都是常见的html标签。

    下面看看上传的代码check_image.php,重要的地方都做了注释,整个过程是先根据那个<input type="file" name="uploadfile"/>指定的图片路径来创建一个图片文件,然后再通过指定的上传路径生成这个图片。

    <?php 
    $db = mysql_connect('localhost','root','Ctrip07185419') or die('can not connect to database');
    mysql_select_db('moviesite',$db) or die(mysql_error($db));
    //上传文件的路径
    $dir = 'D:Seriousphpdev	estimages';
    /*
    $_FILES:用在当需要上传二进制文件的地方,获得该文件的相关信息
    $_FILES['userfile']['name'] 客户端机器文件的原名称。 
    $_FILES['userfile']['type'] 文件的 MIME 类型,需要浏览器提供该信息的支持,例如“image/gif” 
    $_FILES['userfile']['size'] 已上传文件的大小,单位为字节
    $_FILES['userfile']['tmp_name'] 文件被上传后在服务端储存的临时文件名,注意不要写成了$_FILES['userfile']['temp_name']很容易写错的,虽然tmp就是代表临时的意思,但是这里用的缩写
    $_FILES['userfile']['error'] 和该文件上传相关的错误代码。['error'] 
    */
    if($_FILES['uploadfile']['error'] != UPLOAD_ERR_OK)
    {
        switch($_FILES['uploadfile']['error'])
        {
            case UPLOAD_ERR_INI_SIZE: //其值为 1,上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值
                die('The upload file exceeds the upload_max_filesize directive in php.ini');
            break;
            case UPLOAD_ERR_FORM_SIZE: //其值为 2,上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值
                die('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.');
            break;
            case UPLOAD_ERR_PARTIAL: //其值为 3,文件只有部分被上传
                die('The uploaded file was only partially uploaded.');
            break;
            case UPLOAD_ERR_NO_FILE: //其值为 4,没有文件被上传
                die('No file was uploaded.');
            break;
            case UPLOAD_ERR_NO_TMP_DIR: //其值为 6,找不到临时文件夹
                die('The server is missing a temporary folder.');
            break;
            case UPLOAD_ERR_CANT_WRITE: //其值为 7,文件写入失败
                die('The server failed to write the uploaded file to disk.');
            break;
            case UPLOAD_ERR_EXTENSION: //其他异常
                die('File upload stopped by extension.');
            break;
        }
    }
    
    $image_caption = $_POST['caption'];
    $image_username = $_POST['username'];
    $image_date = date('Y-m-D');
    /*getimagesize方法返回一个数组,
    $width : 索引 0 包含图像宽度的像素值,
    $height : 索引 1 包含图像高度的像素值,
    $type : 索引 2 是图像类型的标记:
    1 = GIF,2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 
    7 = TIFF(intel byte order),8 = TIFF(motorola byte order),
    9 = JPC,10 = JP2,11 = JPX,12 = JB2,13 = SWC,14 = IFF,15 = WBMP,16 = XBM,
    $attr : 索引 3 是文本字符串,内容为“height="yyy" width="xxx"”,可直接用于 IMG 标记
    */
    
    list($width,$height,$type,$attr) = getimagesize($_FILES['uploadfile']['tmp_name']);
    
    //imagecreatefromgXXX方法从一个url路径中创建一个新的图片
    switch($type)
    {
        case IMAGETYPE_GIF:
            $image = imagecreatefromgif($_FILES['uploadfile']['tmp_name']) or die('The file you upload was not supported filetype');
            $ext = '.gif';
        break;
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']) or die('The file you upload was not supported filetype');
            $ext = '.jpg';
        break;    
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng($_FILES['uploadfile']['tmp_name']) or die('The file you upload was not supported filetype');
            $ext = '.png';
        break;    
        default    :
            die('The file you uploaded was not a supported filetype.');
    }
    
    $query = 'insert into images(image_caption,image_username,image_date) values ("'.$image_caption.'","'.$image_username.'",now())';
    mysql_query($query , $db) or die(mysql_error($db));
    $last_id = mysql_insert_id();
    //用写入的id作为图片的名字,避免同名的文件存放在同一目录中
    $imagename = $last_id.$ext;
    $query = 'update images set image_filename="'.$imagename.'" where image_id='.$last_id;
    mysql_query($query , $db) or die(mysql_error($db));
    //有url指定的图片创建图片并保存到指定目录
    switch($type)
    {
        case IMAGETYPE_GIF:
            imagegif($image,$dir.'/'.$imagename);
        break;
        case IMAGETYPE_JPEG:
            imagejpeg($image,$dir.'/'.$imagename);
        break;
        case IMAGETYPE_PNG:
            imagepng($image,$dir.'/'.$imagename);
        break;
    }
    //销毁由url生成的图片
    imagedestroy($image);
    ?>
    
    <html>
        <head>
            <title></title>
        </head>
        <body>
            <h1>So how does it feel to be famous</h1>
            <p>Here is the picture you just upload to servers</p>
            <img src="images/<?php echo $imagename;?>" alt="upload image" />
            <table>
            <tr>
                <td>Image save as:</td><td><?php echo $imagename?></td>
                <td>Image type:</td><td><?php echo $ext?></td>
                <td>Height:</td><td><?php echo $height?></td>
                <td>Width:</td><td><?php echo $width?></td>
                <td>Upload date:</td><td><?php echo $image_date?></td>
            </tr>
            </table>
        </body>
    </html>

    最后写道数据库中的信息如下:

    在upload_image.php这个页面中同图片file控件使用户可以通过浏览自己的本地文件选择要上传的文件,其次还要对form的enctype属性进行设置,这里需要上传文件所以在发送到服务器之前不对表单数据进行编码,需要将值设置成mulitpart/form-data,还要注意这里method属性应该设置成post,如果设置成get的话,不能正常地上传文件。

    在check_image.php这个页面中则需要检查文件类型,然后将文件信息写入到数据库中,最后在指定的路径中写入文件并输出文件信息,如果不符合类型或者写入的过程中有错误则会输出错误并跳出程序,输出错误信息。

    php中使用$_FILES数组来存储上传的文件信息,这个数组是多维的,第一维的KEY是上传控件的name属性值,如果在一个页面中有多个上传控件的话可以使用不同的KEY值来区分它,第二维参数名字及含义如下:

       name:在本地的文件名字
       type:图片文件的扩展名字
       size:图片文件的大小以byte来计算
       tmp_name:在上传到的新的目录上的文件名字
       error:上传过程中出现的错误
    在上传到目录之前文件以一种临时文件的形式出现,上传完之后一定要销毁这个临时文件。

    type属性是要上传文件的扩展名字,例如:image/jpg,image/gif,记住这个名字是通过浏览器来获得的,可能不正确,不怀好意的用户可能会伪造这个文件扩展名。

    size属性表示要上传文件的大小,它是以byte来计算,

    error属性来告诉客户端上传过程中的一些错误代码,通过这些代码将能编写出更加健壮的程序,error的枚举值如下:

    UPLOAD_ERR_OK:文件上传成功
    UPLOAD_ERR_INI:上传文件超过php.ini文件中规定最大上传文件大小
    UPLOAD_ERR_FORM_SIZE:上传文件超过HTML文件中规定的文件上传大小限制
    UPLOAD_ERR_PARTIAL:上传的文件不完整
    UPLOAD_ERR_NO_FILE:php.ini中没有指定临时文件夹
    UPLOAD_ERR_CANT_WRITE:文件夹没有写入权限,php不能写入
    UPLOAD_ERR_EXTENSION:上传文件被php中断

    很多地方可以对上传文件进行限制,当上传文件大小超过php.ini中文件大小的时候将返回UPLOAD_ERR_INI值,默认情况下这个值是2M,如下:

    upload_max_filesize = 2M
    如果要修改这个值,可能还需要同时修改 post_max_size这个,upload_max_filesize限制上传文件的大小,post_max_size限制整个post数据大小,所以如果upload_max_filesize大于post_max_size,上传也可能失败,所以这两个值的关系应该是post_max_size大于upload_max_filesize。

    当文件大小大于html页面中一个特定的隐藏域设置大小的时候将返回UPLOAD_ERR_FORM_SIZE,这个隐藏域的设置如下:
    <input type=”hidden” name=”MAX_FILE_SIZE”  value=”262144”/>
    <input type=”file” name=”uploadfile”/>

     要注意的是这个隐藏域的位置应该在上传控件之上。这个值不一定有用,不怀好意的人可能在上传过程中修改文件的大小信息进而蒙骗服务器。正常情况下这个值还是有用的,可以用它来显示文件大小超过限制的信息。

    当文件上载成功之后,getimagesize()方法可以返回一个5个元素的数组,用来获取文件的信息,例如:

    下标为0的元素:图片的宽度
    下标为1的元素:图片的高度
    下标为2的元素:一个枚举,表示图片的类型
    下标为3的元素:一个字符串类似于height=“ yyy ”   width=“ xxx ”
    下标为4的元素:文件的扩展名称,简单说还是文件的类型

     确定图片类型之后,将文件读入内存,imagecreatefrom*()方法打开文件并返回句柄,记住文件是首先放到一个临时的文件夹中,然后再写入到最终路径中,最后销毁,通常是使用 move_uploaded_file() 方法来实现的,第一个参数是要文件名字,第二个参数是文件上传的路径,如果文件类型是非法的话imagecreatefrom*()方法会返回错误。

    同时根据文件类型制定文件扩展,如果上传的文件不再指定的范围内,将返回信息The file you uploaded was not a supported filetype。如果一切进行的顺利的话,将文件信息写入倒数据库中。

    最后imagegif() ,    imagejpeg() , imagepng() 这类方法将文件通过$image方法得到的结果写入到指定的文件名中,imagejpeg()方法有第三个参数,这个参数将会影响图片的质量,100表示最小的压缩比例,质量也是最好的,同理0质量是最差的。

    imagedestroy()方法将$image方法占用的内存资源释放掉,php会自动释放掉这些资源,但是如果手动释放表示我们有一个好的习惯。最后将上传的文件显示在页面中,表示已经上传成功。

  • 相关阅读:
    greenplum导数据
    greenplum 集群部署
    jmx远程访问权限设置
    分布式实时日志处理平台ELK
    hbase0.95.2部署
    hadoop2.2.0部署
    highcharts
    FreeMarker
    使用solr的完整流程
    solr搜索流程
  • 原文地址:https://www.cnblogs.com/tylerdonet/p/3717740.html
Copyright © 2011-2022 走看看