在上传之前获取图像的宽度和高度

时间:2015-08-29 16:06:09

标签: php file-upload

我一直在尝试这段代码:

$file_tmp = $_FILES['video_imagen']['tmp_name'];
list($width, $height) = getimagesize($file_tmp);

但它给了我一个错误。我无法修复它

已更新

这里有你开发的PHP代码。我该如何解决呢?我一直在不同的论坛寻找解决方案......

我收到此错误

  

注意:getimagesize():读取错误!在第282行的C:\ wamp \ www \ tapeHD \ include \ php \ database.php

    public static function SubirVideo($titulo, $video_directorio, $imagen_directorio, $user, $descripcion){
        //ID AUTO INCREMENT
        $sql = "INSERT INTO video(nombre, directorio, imagen, visitas, likes, usuario_id, fecha_subida, descripcion) VALUES ($titulo, $video_directorio, $imagen_directorio, 0, 0, $user, NOW(), $descripcion)";
        $resultado = self::Conexion($sql);
        return $resultado;
    }

    public static function SubirVideoErrores(){
        $error = "";

        if(isset($_POST["boton_upload_video"])){
            $uploadImagen = $_FILES['video_imagen']['name'];
            $tipoImagen = $_FILES['video_imagen']['type'];

            $uploadVideo = $_FILES['video_file']['name'];
            $tipoVideo = $_FILES['video_file']['type'];

            $titulo = $_POST["video_title"];
            $descripcion = $_POST["video_description"];

            $directorio = $_SERVER['DOCUMENT_ROOT']."/tapeHD/include/database/usuarios/".$_SESSION["usuario"]."/videos";

            if($tipoImagen == "image/jpeg"){
                $file_tmp = $_FILES['video_imagen']['tmp_name'];
                list($width, $height) = getimagesize($file_tmp);

                if($_FILES['video_imagen']['size'] < (1024000)){
                    if($width != 320 && $height != 180){
                        $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>La imagen debe de ser 320x180</div></div></div>";
                    } else {
                        if($tipoVideo == "video/mp4"){
                            move_uploaded_file($_FILES['video_file']['tmp_name'], $directorio."/".$uploadVideo);
                            move_uploaded_file($_FILES['video_imagen']['tmp_name'], $directorio."/".$uploadImagen);
                            $video_directorio = "include/database/usuarios/".$_SESSION["usuario"]."/videos/".$uploadVideo;
                            $imagen_directorio = "include/database/usuarios/".$_SESSION["usuario"]."/videos/".$uploadImagen;
                            DataBase::SubirVideo($titulo, $video_directorio, $imagen_directorio, $_SESSION["usuario"], $descripcion);
                            $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>Tu video ha sido subido</div></div></div>";
                        } else {
                            $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>El video debe estar en formato .mp4</div></div></div>";
                        }
                    }
                } else {
                    $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>La imagen pesa demasiado</div></div></div>";
                }
            } else {
                $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>La imagen debe ser .jpg </div></div></div>";
            }
        }
        return $error;  
    }

HTML

            <div class="upload_video_fields">
                <div class="container">
                    <form action="upload.php" method="POST" enctype="multipart/form-data">
                        <div class="video_form left">
                            <input type="text" id="video_title" name="video_title" placeholder="Título del video..." required />
                            <textarea id="video_description" name="video_description" placeholder="Descripción del video..." cols="40" rows="6" aria-required="true" required></textarea>

                        </div>

                        <div class="video_form right">
                            <input type="file" id="video_imagen" name="video_imagen" required />

                            <input type="file" id="video_file" name="video_file" required />
                        </div>
                        <input type="submit" id="boton_upload_video" name="boton_upload_video" class="btn" value="Subir" />
                    </form>
                </div>

                <div class="upload_progress"><div class="bar"></div></div>
            </div>

2 个答案:

答案 0 :(得分:1)

对于多个文件上传,以下内容来自手册 - 以防您无法找到。我希望在上传后尝试访问变量时,这可以提供足够的指导。

-----------------------------------
Example #1 Uploading multiple files
-----------------------------------
<form action="file-upload.php" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="userfile[]" type="file" /><br />
  <input name="userfile[]" type="file" /><br />
  <input type="submit" value="Send files" />
</form>

提交上述表单后,数组$_FILES['userfile']$_FILES['userfile']['name']$_FILES['userfile']['size']将被初始化。其中每个都是数字索引数组提交文件的适当值。

例如,假设提交了文件名/home/test/review.html/home/test/xwp.out。在这种情况下,$_FILES['userfile']['name'][0]将包含值review.html,而$_FILES['userfile']['name'][1]将包含值xwp.out

同样,$_FILES['userfile']['size'][0]将包含review.html的文件大小,依此类推。

答案 1 :(得分:0)

Subirvideo函数中的sql看起来不正确,因为没有值包含引号。从技术上讲,不需要围绕整数值的引号,但不会造成任何伤害。我在exit语句中添加了sql,以便你可以检查结果,虽然你现在说它很好。主要方法SubirVideoErrores有一些额外的代码可以将上传的图像调整为指定的最大尺寸(同时希望保持纵横比)

public static function SubirVideo( $titulo, $video_directorio, $imagen_directorio, $user, $descripcion ){
    /* note: 
       Ensure that $titulo and $descripcion are properly escaped to avoid issues with quote marks etc
    */
    $sql = "INSERT INTO `video` ( `nombre`, `directorio`, `imagen`, `visitas`, `likes`, `usuario_id`, `fecha_subida`, `descripcion` )
            VALUES
            ( '$titulo', '$video_directorio', '$imagen_directorio', '0', '0', '$user', now(), '$descripcion' )";

    /* Remove if the exit( sql ) if it looks correct */
    exit( $sql );
    $resultado = self::Conexion( $sql );
    return $resultado;
}

public static function SubirVideoErrores( $force_resize=true ){
    /* set the default value of $force_resize to false if you do not wish resizing by default */
    try{
        $error = "";

        $max_width=320;
        $max_height=180;

        /* I added this so I could set a var rather than use a session for testing, ie: $session_usuario='antonio' etc */
        $session_usuario=$_SESSION["usuario"];

        if( isset( $_POST["boton_upload_video"] ) ){

            $titulo = $_POST["video_title"];
            $descripcion = $_POST["video_description"];

            $uploadImagen = $_FILES['video_imagen']['name'];
            $tipoImagen = $_FILES['video_imagen']['type'];
            $uploadVideo = $_FILES['video_file']['name'];
            $tipoVideo = $_FILES['video_file']['type'];

            /* Check for errors */
            $video_upload_error = intval( $_FILES['video_file']['error'] );
            $image_upload_error = intval( $_FILES['video_imagen']['error'] );

            if( $video_upload_error > 0 or $image_upload_error > 0 ){
                exit('There were errors during the upload process');    
            }

            if( !empty( $uploadVideo ) && !empty( $uploadImagen ) ){

               $directorio = $_SERVER['DOCUMENT_ROOT']."/tapeHD/include/database/usuarios/".$session_usuario."/videos";
               #$directorio = 'c:/temp/uploads_testing';

                if( $tipoImagen !== "image/jpeg"){
                    $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>La imagen debe ser de formato .jpg</div></div></div>";
                    print $error;

                } else {

                    list( $width, $height, $type, $attr ) = getimagesize( $_FILES["video_imagen"]["tmp_name"] );

                    if( $force_resize==true ){
                        /* Resize supplied mage to a maximum of 320x180 if it is larger then these sizes */
                        if( $width > $max_width or $height > $max_height ) {
                            if( $width > $height ){
                                /* landscape */
                                $aspect = $max_width / $width;
                                $new_width = $max_width;
                                $new_height = $height * $aspect;
                            } elseif( $width == $height ){
                                /* square */
                                $new_width=$max_height;
                                $new_height=$max_height;
                            } else {
                                /* portrait */
                                $aspect = $max_height / $height;
                                $new_width = $width * $aspect;
                                $new_height = $max_height;  
                            }

                            $uploadedimgpath=$directorio."/".$uploadImagen;

                            move_uploaded_file( $_FILES['video_file']['tmp_name'], $directorio."/".$uploadVideo );
                            move_uploaded_file( $_FILES['video_imagen']['tmp_name'], $uploadedimgpath );                        

                            $image = @imagecreatetruecolor( $new_width, $new_height );
                            $background_color = @imagecolorallocate( $image, 255, 255, 255 );
                            $source = @imagecreatefromjpeg( $uploadedimgpath );

                            @imagecopyresampled( $image, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height ); 
                            @imagejpeg( $image, $uploadedimgpath, 100 ); 
                            @imagedestroy( $image ); 
                            @imagedestroy( $source );

                            $width=$new_width;
                            $height=$new_height;
                        }
                    } else {
                            $uploadedimgpath=$directorio."/".$uploadImagen;

                            move_uploaded_file( $_FILES['video_file']['tmp_name'], $directorio."/".$uploadVideo );
                            move_uploaded_file( $_FILES['video_imagen']['tmp_name'], $uploadedimgpath );
                    }

                    if( $_FILES['video_imagen']['size'] > 1024000 ){
                        $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>La imagen pesa demasiado</div></div></div>";
                        print $error;

                    } else {

                        if( $width == 320 or $height == 180 ){
                            if( $tipoVideo == "video/mp4" ){

                                $video_directorio = "include/database/usuarios/".$session_usuario."/videos/".$uploadVideo;
                                $imagen_directorio = "include/database/usuarios/".$session_usuario."/videos/".$uploadImagen;

                                DataBase::SubirVideo( $titulo, $video_directorio, $imagen_directorio, $session_usuario, $descripcion );

                                $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>Tu video ha sido subido</div></div></div>";
                                print $error;
                            } else {
                                $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>El video debe estar en formato .mp4</div></div></div>";
                                print $error;
                            }
                        } else {
                            $error = "<div id='error_alert'><div class='error_container'><i class='fa fa-times awesome error_close btn'></i><div class='error_text'>La imagen debe de ser 320x180</div></div></div>";
                            print $error;
                        }
                    }
                }
            }
        }
    }catch( Exception $e ){
        exit( $e->getMessage() );   
    }
}

我已对此进行了测试,图像和视频都可以在我的系统上正常上传(当然有一些路径更改),并且两者都是可读的。我可以观看上传的视频并查看上传的图像 - 即使是那些调整大小的图像。您上传的视频是否非常大?