正在尝试使用我的uploadImage功能进行pdf上传


Trying to use my uploadImage function for pdf upload

Im使用uploadImage函数上传图像。

现在我也尝试上传pdf,做了一些更改,使用相同的功能,但没有创建其他功能,但我没有成功。

有没有像imagejpeg()这样的pdf方法,所以我可以做一些类似的事情上传到我的文件夹:

case 'pdf': filepdf($new_img, $folder.$name); break;

当然,我不想要调整大小的部分,并处理透明度、混合等效果,但我只想把文件上传到文件夹的部分,但它不起作用。

function uploadImage($tmp, $name, $width, $folder){
        $ext = substr($name,-3);
        switch($ext){
            case 'jpg': $img = imagecreatefromjpeg($tmp); break;
            case 'png': $img = imagecreatefrompng($tmp); break;
            case 'gif': $img = imagecreatefromgif($tmp); break; 
        }       
        $x = imagesx($img);
        $y = imagesy($img);
        $height = ($width*$y) / $x;
        $new_img = imagecreatetruecolor($width, $height);
        imagealphablending($new_img,false);
        imagesavealpha($new_img,true);
        imagecopyresampled($new_img, $img, 0, 0, 0, 0, $width, $height, $x, $y);
        switch($ext){
            case 'jpg': imagejpeg($new_img, $folder.$name, 100); break;
            case 'png': imagepng($new_img, $folder.$name); break;
            case 'gif': imagegif($new_img, $folder.$name); break;   
        }
        imagedestroy($img);
        imagedestroy($new_img);
    }

我还没有测试过这段代码,但你可以尝试一下。。。它检查MIME类型,这比您当前的方法要好。将其重命名为类似uploadFile而不是uploadImage的名称可能是有意义的。并且$width变量对于非图像文件不再有意义。

function uploadImage($tmp, $name, $width, $folder) {
    // initialize variables
    $img = $ext = null;
    // supported file types
    $valid_mimes = array('pdf' => 'application/pdf',
                         'jpg' => 'image/jpeg',
                         'png' => 'image/png',
                         'gif' => 'image/gif');
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if ($ext = array_search($finfo->file($tmp), $valid_mimes, true)) {
        switch($ext) {
            case 'pdf': move_uploaded_file($tmp, $folder.$name); break;
            case 'jpg': $img = imagecreatefromjpeg($tmp); break;
            case 'png': $img = imagecreatefrompng($tmp); break;
            case 'gif': $img = imagecreatefromgif($tmp); break;
        }
        if (isset($img)) {
            $x = imagesx($img);
            $y = imagesy($img);
            $height = ($width*$y) / $x;
            $new_img = imagecreatetruecolor($width, $height);
            imagealphablending($new_img,false);
            imagesavealpha($new_img,true);
            imagecopyresampled($new_img, $img, 0, 0, 0, 0, $width, $height, $x, $y);
            switch($ext) {
                case 'jpg': imagejpeg($new_img, $folder.$name, 100); break;
                case 'png': imagepng($new_img, $folder.$name); break;
                case 'gif': imagegif($new_img, $folder.$name); break;
            }
            imagedestroy($img);
            imagedestroy($new_img);
        }
    }
}