使用Ajax和PHP在CodeIgniter中上传多个图像文件
P粉252116587
P粉252116587 2024-04-03 22:35:03
0
1
512

我在将多个图像文件上传到服务器端时遇到问题。如果有人能够突出显示代码的问题所在,那就太好了。

最初有 HTML 代码:

<label class="col-form-label"><h4>Upload Images</h4></label>
              <div id="image-preview-container">
                <!-- Preview images will be displayed here -->
              </div>
              <form id="uploadCert" enctype="multipart/form-data">
                <input type="file" id="images" name="images" multiple="multiple" accept="image/*" style="display: none;">
                <label for="images" class="btn btn-primary"> Add Image </label>
              </form>
            </div>

在 JavaScript 中定义

var selectedImages = []; //list of files in array

并捕获每个选定的文件

$("#images").change(function () {
  var file = this.files[0];

  if (file) {
    ...

    // Append the container to the image preview container
    $("#image-preview-container").append(imageContainer);

    ..

    // Add the selected image file to the postData.images array
    selectedImages.push(file);
    
    $(this).val("");
  }
});

提交后使用 AJAX

$('#addcart').click(function () {

        // Add other form fields to formData
        var formData = new FormData();
        ...
        formData.append("issuesBody", $("#fbody_").val());
        ...
        
        if (selectedImages.length > 0) {
            // Append each selected image to formData
            for (var i = 0; i < selectedImages.length; i++) {
                var image = selectedImages[i];
                if (image instanceof File) {
                  // If it's a File object, append it to formData
                  formData.append("images[]", image);

                }
            }
        } else {
            // If no selected images, set images[] to an empty array
            formData.append("images[]", []);
        }

        // Make the AJAX request
        event.preventDefault();
        $.ajax({
            url: "addcert",
            type: "POST",
            data: formData,
            dataType:"json",
            contentType:false,
            cache:false,
            processData: false,
            success: function(data){
                // Handle a successful response
                ...
            },
            error: function (xhr, status, error) {
                // Handle an error response
                ...
            }
        });

     });


});

在 PHP

private function addNewCert(){
        // Capture POST data
        $issuesBody = $this->input->post('issuesBody'); 
        // Not sure if this is the way to capture the posted file data
        $images = $_FILES['images']; 

        // Upload images to the server
        $uploadedFiles = $this->uploadimg($images);

        //Check if image uploads were successful
        if ($uploadedFiles === false) {
            // Handle the case where image uploads failed
            ...
            echo json_encode($output);
            return;
        } ...

最后在 uploadimg() 期间始终显示 'undefined' 以及这里的代码

private function uploadimg($images) {
        $uploadedFiles = array(); // captured uploaded file name

        // Loop through each uploaded file
        for ($i = 0; $i < count($images['name']); $i++) {
            // Generate a unique file name or use the original name
            $originalFileName = $images['name'][$i];
            $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION);
            $file_name = uniqid() . '_' . $originalFileName;

            $config['upload_path'] = $this->uploadPath;
            $config['file_name'] = $file_name;
            $config['allowed_types'] = 'jpg|jpeg|png|gif'; 
            $config['max_size'] = 2048; 
            $config['encrypt_name'] = TRUE; 

            $this->load->library('upload', $config);

            // Perform the upload
            if ($this->upload->do_upload('images')) {
                $uploadedFiles[] = $file_name;
            } else {
                // Handle the case where an upload failed
                return false;
            }
        }

        return $uploadedFiles;
    }

P粉252116587
P粉252116587

全部回复(1)
P粉268654873

实际上,代码中存在不止一个问题。首先,您应该将 $this->load->library('upload',$config) 语句从 for 循环中取出。您需要从列表中的每个文件创建单个文件才能上传。如果我没有记错的话,Codeigniter do_upload 方法不适用于多个文件。您可以更新您的 uploadimg 方法,如下所示:

private function uploadimg($images) {
    $uploadedFiles = array(); // captured uploaded file name

    $config = [
        'upload_path' => './testUploads/',
        'allowed_types' => 'jpg|jpeg|png|gif',
        'max_size' => 2048,
        'encrypt_name' => TRUE,
    ];
    $this->load->library('upload', $config);

    // Loop through each uploaded file
    for ($i = 0; $i upload->initialize($config);

        $_FILES['singleImage']['name']     = $file_name;
        $_FILES['singleImage']['type']     = $images['type'][$i];
        $_FILES['singleImage']['tmp_name'] = $images['tmp_name'][$i];
        $_FILES['singleImage']['error']    = $images['error'][$i];
        $_FILES['singleImage']['size']     = $images['size'][$i];
        

        // Perform the upload
        if ($this->upload->do_upload('singleImage')) {
            $uploadedFiles[] = $file_name;
        } else {
            // Handle the case where an upload failed
            return false;
        }
    }

    return $uploadedFiles;
}

P.S 我明白了,您正在生成一个更易读的文件名。如果您想查找具有该命名结构的文件,则应将配置数组中的 encrypt_name 字段设置为 false。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板