如何在上传时重命名多个文件

时间:2013-07-09 17:09:55

标签: php file-upload

我在这里遇到一个小问题。我有以下表单,用于允许用户上传一个或多个文件:

<form action="RejoinReq.php" method="post" enctype="multipart/form-data">
    Attachment 1: <input type="file" name="file[]" id="file" maxlength="500" accept="application/pdf,image/*" />
    <input type="submit" name="submit" value="Request" />
</form>

接下来,我需要在将文件保存到服务器之前重命名文件。为此,我试图使用:

RejoinReq.php

<?php

function findexts ($filename) {
    $filename = strtolower($filename);
    $exts = explode(".", $_FILES["file"]["name"]);
    $n = count($exts) - 1;
    $exts = $exts[$n];
    return $exts;
}
$ext = findexts($_FILES['file']['name']);
$target = "upload/";
$target = $target . $_SESSION['myusername'] . "Rejoin." . $ext;
if (file_exists("upload/" . $_FILES["file"]["name"])) {
    //echo $_FILES["file"]["name"] . " already exists. ";
}
else {
    move_uploaded_file($_FILES["file"]["tmp_name"],$target);
    //echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}

已更新 - 对PHP代码的修改

  

警告:findexts()期望参数1为字符串,给定数组

     

警告:move_uploaded_file()期望参数1为字符串,给定数组

3 个答案:

答案 0 :(得分:2)

此代码需要完全重写才有用。

<?PHP
$filekeys=array_keys($_FILES);
foreach($filekeys as $activefile)
    {
    if($_FILES[$activefile]['error']==0)

        {
        $file= fopen($_FILES[$activefile]['tmp_name'],'r');
        $content = fread($file, filesize($_FILES[$activefile]['tmp_name']));
        fclose($file);
            //determine $target here
            $file2= fopen($target,"w");
            fwrite($file2,$content);
            fclose($file2);
            }
    }
?>

此代码适用于任意数量的文件,但您需要处理将$ target更改为每个文件的所需内容。

这有点过于复杂,但它确实允许你操纵$ content。它改编自我用于将加密文件存储在数据库中的一些代码,因此需要提取文件内容。

答案 1 :(得分:1)

在这里,这应该就是你所需要的一切!

index.html ,格式为:

<form action="RejoinReq.php" method="post" enctype="multipart/form-data">
    Attachment(s): <input type="file" name="file[]" id="file" maxlength="500" accept="application/pdf,image/*" multiple>
    <input type="submit" name="submit" value="Request">
</form>

接收 RejoinReq.php

<?php

// config
$upload_dir = '/var/www/html/upload'; // set your upload dir
$max_size = 1048576; // max file size: 1 MB
$allow_override = FALSE; // allow uploading files overriding existing ones
$valid_exts = array( // allowed extensions
    'gif',
    'jpeg',
    'jpg',
    'png',
    'pdf',
);
$valid_types = array(
    'image/gif',
    'image/jpeg',
    'image/jpg',
    'image/pjpeg',
    'image/x-png',
    'image/png',
    'text/pdf',
    'application/pdf',
);

// reorganize files array
$files = array();
foreach ($_FILES['file'] as $attr => $arr) {
    foreach ($arr as $k => $v) {
        $files[$k][$attr] = $v;
    }
}

// loop thru files
foreach ($files as $file) {
    $status = 'Failure';

    // get extension
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);

    // make sure extension and type are not empty
    if ( ! (strlen($extension) && strlen($file['type']))) {
        $msg = 'File extension or type not found';
    }
    else {

        // make sure extension and type are allowed
        if ( ! (in_array($file['type'], $valid_types) && in_array($extension, $valid_exts))) {
            $msg = "Extension '$extension' or file type '$file[type]' is not permitted";
        }
        else {

            // make sure file is not empty
            if ( ! $file['size']) {
                $msg = 'File seems to be empty (0 KB)';
            }
            else {

                // make sure file is not too large
                if ($file['size'] > $max_size) {
                    $msg = 'File is too large (' . ceil($file['size'] / 1024) . 'kB > ' . floor($max_size / 1024) . 'kB)';
                }
                else {

                    // rename file here as you need
                    $target = "$upload_dir/$_SESSION[myusername]Rejoin.$file[name]";

                    // make sure files don't override
                    if ( ! $allow_override && file_exists($target)) {
                        $msg = "File already exists";
                    }
                    else {

                        // no other errors
                        if ($file['error'] > 0) {
                            $msg = "Unknown upload error (Code: $file[error])";
                        }
                        else {

                            // attempt uploading
                            if ( ! move_uploaded_file($file['tmp_name'], $target)) {
                                $msg = 'Upload failed. Folder issues?';
                            }
                            else {

                                // all good!
                                $msg = 'Upload successful!';
                                $status = 'Success';
                            }
                        }
                    }
                }
            }
        }
    }
    $out[] = "$file[name]: $status. $msg";
}

echo implode("\n", $out);

/* End of file */

答案 2 :(得分:0)

试试这个:

<?php

class Upload_Rename{


    const ALLOWED_TYPES = "jpg,gif,png";

    public static function generate_new_name($extension,$uppercase=true,$prefix='',$sufix=''){
        $new_name = $prefix.uniqid().'_'.time().$sufix;
        return ($uppercase ? strtoupper($new_name) : $new_name).'.'.$extension;
    }

    public static function check_and_get_extension($file){

        $file_part      = pathinfo($file);
        $allowed_types  = explode(",",Upload_Rename::ALLOWED_TYPES);

        if(!in_array($file_part['extension'], $allowed_types)){
            throw new Exception('Not ok.. bad bad file type.');
        }

        return $file_part['extension'];
    }


    public function upload($file,$target_destination){

        if(!isset($file['tmp_name'])){
            throw new Exception('Whaaaat?');
        }

        $_name   = $file['name'];
        $_tmp    = $file['tmp_name'];
        $_type   = $file['type'];
        $_size   = $file['size'];


        $file_extension = '';

        try{
            $file_extension = Upload_Rename::check_and_get_extension($_name);
        }catch(Exception $e){
            throw new Exception('Ops.. file extension? what? '.$e->getMessage());
        }

        $new_name    = Upload_Rename::generate_new_name($file_extension,true,'whaat_','_okey');
        $destination = $target_destination . DIRECTORY_SEPARATOR . $new_name;

        return move_uploaded_file($_tmp, $destination);
    }

    public function multiple_files($files,$destination){

        $number_of_files = isset($files['tmp_name']) ? sizeof($files['tmp_name']) : 0;

        $errors = array();

        for($i=0;$i<$number_of_files;$i++){
            if(isset($files['tmp_name'][$i]) && !empty($files['tmp_name'][$i])){
                try{
                    $this->upload(array(
                        'name'=>$files['name'][$i],
                        'tmp_name'=>$files['tmp_name'][$i],
                        'size'=>$files['size'][$i],
                        'type'=>$files['type'][$i]
                    ),$destination);
                }catch(Exception $e){
                    array_push($errors,array('file'=>$files['name'][$i],'error'=>$e->getMessage()));
                }
            }
        }

        print_r($errors);
    }

}

if($_FILES){
    $upload = new Upload_Rename();
    $destination = dirname(__FILE__);
    $upload->multiple_files($_FILES['myfile'],$destination);
}
?>

<form  method="post" enctype="multipart/form-data">
    <?php for($i=0;$i<10;$i++): ?>
    file: <input type="file" name="myfile[]"><hr>
    <?php endfor; ?>
    <input type="submit">
</form>