多文件上传-当所有文档都上传失败而输入的文件很少时效果很好

Priyeshrulz

我有此表格,需要上传多个文件(最多10个文件)。这是html的样子:

<form action="fileupload.php" method="post" enctype="multipart/form-data">
<tr><td><input type="hidden" name="consultant_id" value="<?php echo $consult_id; ?>"></td></tr>

<tr><td>Offer letter:</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td>Project acceptance agreement:</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td>Employee book:</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td>W4 :</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td>State W4 :</td><td> Doc: <input type="file" name="myfile[]"></td></tr>
<tr><td><input type="submit" name="submit" value="Upload">  </td></tr>
</form></table>

我想将文件上传到服务器,并将它们各自的路径存储在database(MySql)中。现在,当我在所有文件字段中输入内容(上传所有10个文件)时,以下php代码非常有用,但在我仅上载一些文件(例如5)时失败。这是代码:

        <?php
    $consultant_id = $_POST['consultant_id'];
    echo $consultant_id;
    $verified_start_date = $_POST['verified_start_date'];

    // Assign valid types
    $valid_mime = array(
        'application/pdf',
        'image/jpeg',
        'image/jpg',



     );

    function upload($files, $dir, $size_limit=1024, $prevent_duplicate=false){
        global $valid_mime;

    // $files must be given.
    if(!isset($files)) return false;

    // Look for $valid_mime array.
    isset($valid_mime) and is_array($valid_mime) or die('Error in data resources, valid_mime array not found.');

    // Make directory if it does not exists. set permission to 0777.
    is_dir($dir) and chmod($dir, 0777) or mkdir($dir, 0777, true);
    //is_dir($consultant_id) and ($dir, 0777) or mkdir($dir/$consultant_id, 0777, true);
    $count = 1;
    foreach($files as $file){
        $file['error'] === UPLOAD_ERR_OK or die('Error in uploading file(s).');

        // Check uploaded-file type.
        in_array($file['type'], $valid_mime) or die();

        // Set size_limit in KB.
        $file['size'] > $size_limit*1024 and die('The uploaded file exceeds the maximum file size.');


        $file_extension = strrchr($file['name'], '.');
        $filename = basename($file['name'], $file_extension);

        $file_path = "{$dir}/{$filename}{$file_extension}";

        // Move uploaded-file from php temp folder to desire one.
        move_uploaded_file($file["tmp_name"], $file_path);

        // Make an array of filepaths
        $output[] = $file_path;
    }

    // Change permission of folder according to security issues.
    chmod($dir, 0755);

    return $output; 
}
/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////  Controller Section  ////////////////////////////////

// Assign tmp_arr from $_FILES['myfile'] and do die if there is any problem.
$tmp_arr = (isset($_POST['submit']) and isset($_FILES['myfile'])) ? $_FILES['myfile'] : die('Error in posting data.');


// Create an array with desired structure.
for($i=0; $i<count($tmp_arr['name']); $i++){
    $files[] = array(
        'name'      =>  $tmp_arr['name'][$i],
        'type'      =>  $tmp_arr['type'][$i],
        'tmp_name'  =>  $tmp_arr['tmp_name'][$i],
        'error' =>  $tmp_arr['error'][$i],
        'size'      =>  $tmp_arr['size'][$i],
    );
}

// size_limit in KB
$path_arr = upload($files, './public/'.$consultant_id, 1024, true);
?>

我没有提到在数据库中输入数据的部分,因为我知道问题出在$ tmp_arr ['error'] [$ i]或$ file ['error'] === UPLOAD_ERR_OK或die('Error in上传文件。');

请看一下。

乔纳森·库恩

问题似乎是当您输入空白文件时,它返回的'error'值为4,表示UPLOAD_ERR_NO_FILE因此,由于该字段不匹配,因此UPLOAD_ERR_OK您可以通过die在复制第一个空格后调用停止任何文件来立即停止所有代码如果第一个字段为空白,则不会有任何结果move_uploaded_file如果十分之三为空白,则前两个文件将被复制,当第三个文件被处理时,它将停止任何其他文件。但是您仍然会看到错误“上传文件时出错”。

编辑:

<?php
$consultant_id = $_POST['consultant_id'];
echo $consultant_id;
$verified_start_date = $_POST['verified_start_date'];

// Assign valid types
$valid_mime = array(
    'application/pdf',
    'image/jpeg',
    'image/jpg',



 );

function upload($files, $dir, $size_limit=1024, $prevent_duplicate=false){
    global $valid_mime;

    // $files must be given.
    if(!isset($files)) return false;

    //please use proper if statements. This is confusing.
    //isset($valid_mime) and is_array($valid_mime) or die('Error in data resources, valid_mime array not found.');

    // Look for $valid_mime array.
    if(!isset($valid_mime) || !is_array($valid_mime)) {
        die('Error in data resources, valid_mime array not found.');
    }

    //please use proper if statements. This is confusing.
    // is_dir($dir) and chmod($dir, 0777) or mkdir($dir, 0777, true);

    // Make directory if it does not exists. set permission to 0777.
    if(!is_dir($dir)) {
        mkdir($dir, 0777, true);
    } else {
        //try to chmod if the directory does exist
        chmod($dir, 0777);
    }

    if(!is_writable($dir)){
        die('Error unable to write to specified directory.');
    }

    foreach($files as $key=>$file){
        //switch case on the error code
        //you can find a list of these error codes at: http://php.net/manual/en/features.file-upload.errors.php
        switch($file['error']){
            default:
                //triggered if an unknown error happened. Newer php versions might bring new constants.
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'An unknown error occurred');
                break;
            case UPLOAD_ERR_INI_SIZE:
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'File size exceeds ini setting');
                break;
            case UPLOAD_ERR_FORM_SIZE:
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'File size exceeds MAX_FILE_SIZE setting');
                break;
            case UPLOAD_ERR_PARTIAL:
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'File was only partially uploaded');
                break;
            case UPLOAD_ERR_NO_FILE:
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'File input was blank');
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'Missing temporary folder');
                break;
            case UPLOAD_ERR_CANT_WRITE:
                //log error for this file
                $output[$key] = array('error'=>true, 'message'=>'Failed to write file to disk');
                break;
            case UPLOAD_ERR_OK:
                //upload worked fine
                // Check uploaded-file type.
                if(in_array($file['type'], $valid_mime)){
                    // Set size_limit in KB.
                    if($file['size'] <= $size_limit*1024){
                        //get the file extension.
                        $file_extension = strrchr($file['name'], '.');
                        //get the filename
                        $filename = basename($file['name'], $file_extension);
                        //full filename and path
                        $file_path = "{$dir}/{$filename}{$file_extension}";

                        // Move uploaded-file from php temp folder to desire one.
                        // function returns true if the move was successful
                        if(move_uploaded_file($file["tmp_name"], $file_path)){
                            $output[$key] = array('error'=>false, 'message'=>'File was uploaded successfully', 'file'=>$file_path);
                        } else {
                            $output[$key] = array('error'=>true, 'message'=>'Unspecified error when moving the uploaded file');
                        }
                    } else {
                        //log error for this file
                        $output[$key] = array('error'=>true, 'message'=>'The uploaded file exceeds the maximum file size');
                    }
                } else {
                    //log error for this file
                    $output[$key] = array('error'=>true, 'message'=>'Failed to write file to disk');
                }
        }
    }

    // Change permission of folder according to security issues.
    chmod($dir, 0755);

    return $output; 
}

/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////  Controller Section  ////////////////////////////////

// Assign tmp_arr from $_FILES['myfile'] and do die if there is any problem.
$tmp_arr = (isset($_POST['submit']) and isset($_FILES['myfile'])) ? $_FILES['myfile'] : die('Error in posting data.');


// Create an array with desired structure.
for($i=0; $i<count($tmp_arr['name']); $i++){
    $files[] = array(
        'name'      =>  $tmp_arr['name'][$i],
        'type'      =>  $tmp_arr['type'][$i],
        'tmp_name'  =>  $tmp_arr['tmp_name'][$i],
        'error' =>  $tmp_arr['error'][$i],
        'size'      =>  $tmp_arr['size'][$i],
    );
}

// size_limit in KB
$path_arr = upload($files, './public/'.$consultant_id, 1024, true);

如果执行此操作,则将使用此功能。如果一个上传的文件有问题,它将不会阻止剩余的文件上传,并将'error'密钥从$ _FILES转换为更加用户友好的消息。您可以轻松地在return数组上循环并检查boolean'error'键以查看特定文件是否有问题。如果“错误”为true,则可以回显该消息,以供用户查看。如果没有错误,则将显示消息“文件已成功上传”。返回数组中的键与传入的数组中的键相同。因此,$ file [0]与$ returnResult [0]是相同的文件,以方便参考。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

多文件上传完成

来自分类Dev

增加最大上传文件大小WordPress多站点

来自分类Dev

带有其他数据的MVC多文件上传

来自分类Dev

前端多文件上传WordPress

来自分类Dev

带有额外inputText的多文件上传

来自分类Dev

使用beego进行多文件上传

来自分类Dev

中止多文件上传AJAX请求

来自分类Dev

Liferay.Upload组件使用多文件上传

来自分类Dev

多文件上传识别

来自分类Dev

CodeIgniter多文件上传不起作用

来自分类Dev

Symfony 3表单多文件上传问题

来自分类Dev

而在WebSphere自由工作Spring MVC的多文件上传

来自分类Dev

如何使用“多文件上传”控件合并多个上传的图像?

来自分类Dev

npm nock:模拟发布多形式上传文件

来自分类Dev

Shopify出道主题中的多文件上传器

来自分类Dev

PHP多文件上传图形检查

来自分类Dev

多文件上传未保存

来自分类Dev

多文件上传错误

来自分类Dev

多文件上传错误

来自分类Dev

多篇文章-上传文件

来自分类Dev

Django的多文件上传代码

来自分类Dev

多文件上传识别

来自分类Dev

在“多文件上传”中,将单个文件上传到PHP的新文件夹中

来自分类Dev

FTP多文件上传PHP

来自分类Dev

Symfony FileFormField - 测试(WebTestCase)多文件上传

来自分类Dev

PHP多文件上传显示每个文件名

来自分类Dev

jQuery文件上传插件,多文件和表单数据

来自分类Dev

多文件上传php for循环

来自分类Dev

reactjs 形式的多文件上传器