dpicx06888 2019-08-02 19:29
浏览 91

如何遍历数组以获取多个要上载的文件

I am running into a scenario that I cannot get more than one file to upload. If I add more than one file, only the last one will send through.

I know an array is needed to be sent and then looped through, so I changed the name of my input to include [] and then tried changing the public function upload. Below you will see the original version of the fileUpload class and then the my attempted updated version.

Here is the original version of the part of my code to get the files moved:

class fileUpload
{
    public function __construct()
    {}
    public function upload() {

        $target_dir = "uploads/";
        $target_file = $target_dir . basename($_FILES["uploadedFile"]["name"]);
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            return 0;
// if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_file)) {
                return basename($_FILES["uploadedFile"]["name"]);
            } else {
                return 0;
            }
        }
    }
}

Here is the updated version of fileUpload.php in an attempt to loop through the array.

class fileUpload
{

    public function __construct()
    {}
    public function upload(&$file_post) {

        $file_ary = array();
        $file_count = count($file_post['name']);
        $file_keys = array_keys($file_post);

        for ($index = 0; $index<$file_count; $index++) {
            foreach ($file_keys as $key) {
                $file_ary[$index][$key] = $file_post[$key][$index];
            }
        }
        $target_dir = "uploads/";
        $target_file = $target_dir . basename($_FILES["uploadedFile"]["name"]);
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            return 0;
// if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_file)) {
                return basename($_FILES["uploadedFile"]["name"]);
            } else {
                return 0;
            }
        }
    }
}

Doing this, I received the following errors:

Notice: Array to string conversion in /php/sharePhotoSend.php on line 30

Fatal error: Uncaught ArgumentCountError: Too few arguments to function fileUpload::upload(), 0 passed in /php/sharePhotoSend.php on line 73 and exactly 1 expected in /php/fileUpload.php:8 Stack trace:

0 /php/sharePhotoSend.php(73): fileUpload->upload()

1 {main} thrown in /php/fileUpload.php on line 8

Here are the lines being referenced:

fileUpload.php Line 8 - public function upload(&$file_post) {

sharePhotoSend.php Line 30 - $projectSubmission_stmt->execute(array($first_name, $last_name, $email, $phone, $company, $details, $fileNameInsert));

Line 73 - $filename = $fu->upload(); Which line 73 is a part of this:

    if (!empty($_FILES['uploadedFile']['name']) && $_FILES['uploadedFile']['error'] != 4) {
            $fu = new fileUpload();
            $filename = $fu->upload();
            $template = str_replace("{filename}", "A file was uploaded. You can download the file from: <a href='https://mbkit.com/php/uploads/{$filename}'>{$filename}</a>", $template);
    //            print_r($template);
    //              echo "Should be working and hitting the if condition";
            if ( !$filename ) {
                echo json_encode(['status_code' => 500,
                    'message' => "We were not able to upload your file at this time."]);
            }
            clearstatcache();

UPDATE - New fileUpload class:

<?php

class fileUpload
{

    public function __construct()
    {}
    public function upload() {

        $file_ary = array();
        $file_count = count($_FILES['uploadedFile']['name']);
        //$file_count = count($_FILES($file_post['name']));

        for ($i = 0; $i<$file_count; $i++) {
//          echo $file['uploadedFile']['name'][$index] . "
";

            $target_dir = "uploads/";
            $target_file = $target_dir . basename($_FILES["uploadedFile"]["name"][$i]);
            $uploadOk = 1;
            $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));        

            // Check if $uploadOk is set to 0 by an error
            if ($uploadOk == 0) {
                return 0;
    // if everything is ok, try to upload file
            } else {
                if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"][$i], $target_file)) {
                    return basename($_FILES["uploadedFile"]["name"][$i]);
                } else {
                    return 0;
                }
            }
        }
    }
}

Communication Class - this sends the attachments

if (!empty($file) && !$recipient && count($file['uploadedFile']['name']) > 1) {

                $f = new ZipArchive();
                $zip = $f->open('uploads/' . $file['uploadedFile']['name'][0] . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE);
                if ($zip) {
                    for ($index = 0; $index < count($file['uploadedFile']['name']); $index++) {
//                        echo $file['uploadedFile']['name'][$index] . "
";
                        $f->addFile($file['uploadedFile']['tmp_name'][$index], $file['uploadedFile']['name'][$index]);
                    }
                    $f->close();

                    $message["attachment[0]"] = curl_file_create("uploads/{$file['uploadedFile']['name'][0]}.zip",
                        pathinfo("uploads/{$file['uploadedFile']['name'][0]}.zip", PATHINFO_EXTENSION),
                        $file['uploadedFile']['name'][0] . ".zip");
                } else {
                    throw new Exception("Could not zip the files.");
                }

            } 
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 优质github账号直接兑换rmb,感兴趣伙伴可以私信
    • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
    • ¥15 安装svn网络有问题怎么办
    • ¥15 Python爬取指定微博话题下的内容,保存为txt
    • ¥15 vue2登录调用后端接口如何实现
    • ¥65 永磁型步进电机PID算法
    • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
    • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
    • ¥15 如何处理复杂数据表格的除法运算
    • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)