无法从多个 html 输入字段中添加或删除图像

san*_*nce 6 html javascript image

我使用https://github.com/promosis/file-upload-with-preview来显示多张图片的预览

var upload = new FileUploadWithPreview('myUniqueUploadId', {
  maxFileCount: 4,
  text: {
    chooseFile: 'Maximum 4 Images Allowed',
    browse: 'Add More Images',
    selectedCount: 'Files Added',
  },
});
Run Code Online (Sandbox Code Playgroud)
.custom-file-container {
  max-width: 400px;
  margin: 0 auto;
}
Run Code Online (Sandbox Code Playgroud)
<link href="https://unpkg.com/file-upload-with-preview@4.0.2/dist/file-upload-with-preview.min.css" rel="stylesheet"/>
<script src="https://unpkg.com/file-upload-with-preview@4.0.8/dist/file-upload-with-preview.min.js"></script>
<form action="save.php" method="post" enctype="multipart/form-data">
  <div class="custom-file-container" data-upload-id="myUniqueUploadId">
    <label>Upload File <a href="javascript:void(0)" class="custom-file-container__image-clear" title="Clear Image">&times;</a></label>
    <label class="custom-file-container__custom-file">
                    <input type="file" name="files[]" class="custom-file-container__custom-file__custom-file-input" accept="image/*" multiple aria-label="Choose File">
                    <input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
                    <span class="custom-file-container__custom-file__custom-file-control"></span>
                </label>
    <div class="custom-file-container__image-preview" style="overflow: auto!important"></div>
  </div>
  <input type="submit" value="Upload Image" name="submit">
</form>
Run Code Online (Sandbox Code Playgroud)

它工作正常,但我不能添加额外的图像是删除图像。

https://github.com/promosis/file-upload-with-preview/issues/30#issuecomment-563352824启用cachedFileArray示例

添加

我添加了 3 张图像进行输入,我在预览中获得了 3 张图像而没有提交表单 我现在添加了 1 张图像 我在预览中获得了 4 张图像,当我提交表单时,我只上传了 1 张图像(最近添加的文件)。

删除

当我上传所有 4 张图像时,删除图像添加了 4 张图像并删除了 1 张图像时发生同样的情况,一切仅在预览时发生,但注意发生在 <input>

----还有其他更好的方法吗(其他代码或库)但我想使用我的自定义上传处理程序。

PHP上传处理程序

$desired_dir = "$_SERVER[DOCUMENT_ROOT]/upload/file/";
$thumb_directory = "$_SERVER[DOCUMENT_ROOT]/upload/thumb/";
$file = [];
$nw = 125;
$nh = 90;
if (!empty($_POST)) {
    if (isset($_FILES['files'])) {
        $uploadedFiles = array();
        foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
            $errors = array();
            $file_name = md5(uniqid("") . time());
            $file_size = $_FILES['files']['size'][$key];
            $file_tmp = $_FILES['files']['tmp_name'][$key];
            $file_type = $_FILES['files']['type'][$key];
            if ($file_type == "image/gif") {
                $sExt = ".gif";
            } elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
                $sExt = ".jpg";
            } elseif ($file_type == "image/png" || $file_type == "image/x-png") {
                $sExt = ".png";
            }
            if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
                $errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
            }
            if ($file_size > 2097152000) {
                $errors[] = 'File size must be less than 2 MB';
            }


            if (empty($errors)) {
                if (is_dir($desired_dir) == false) {
                    mkdir("$desired_dir", 0700);
                }
                $file_name_with_ext = $file_name . $sExt;
                $source = $desired_dir . $file_name_with_ext ;
                if(!move_uploaded_file($file_tmp, $source)) {
                    echo "Couldn't upload file " . $_FILES['files']['tmp_name'][$key];
                    $file[] = NULL;
                }else{
                    $size = getimagesize($source);
                    $w = $size[0];
                    $h = $size[1];
                    switch ($sExt) {
                        case '.gif':
                            $simg = imagecreatefromgif($source);
                            break;
                        case '.jpg':
                            $simg = imagecreatefromjpeg($source);
                            break;
                        case '.png':
                            $simg = imagecreatefrompng($source);
                            break;
                    }
                    $dest = $thumb_directory. $file_name_with_ext ;
                    $dimg = resizePreservingAspectRatio($simg, $nw, $nh);
                    imagepng($dimg, $dest);
      // imagewebp($dimg, $dest);
                    compress($source, "$desired_dir"  . $file_name_with_ext , 50);
                    compress($dest, $dest , 50);
                    $file[] =   $file_name_with_ext ;
                }
            }else{
                // TODO: error handling
            } 
        }

    }

    $stmt = $conn->prepare("INSERT INTO allpostdata(im1, im2, im3, im4)"
            . " VALUES (:im1, :im2, :im3, :im4)");

    $stmt->bindParam(':im1', $file[0], PDO::PARAM_STR, 100);
    $stmt->bindParam(':im2', $file[1], PDO::PARAM_STR, 100);
    $stmt->bindParam(':im3', $file[2], PDO::PARAM_STR, 100);
    $stmt->bindParam(':im4', $file[3], PDO::PARAM_STR, 100);
    if ($stmt->execute()) {
        header('Location: https://google.com');
    }exit;
}

function compress($source, $destination, $quality) {
    $info = getimagesize($source);
    if ($info['mime'] == 'image/jpeg') {
        $image = imagecreatefromjpeg($source);
    } elseif ($info['mime'] == 'image/gif') {
        $image = imagecreatefromgif($source);
    } elseif ($info['mime'] == 'image/png') {
        $image = imagecreatefrompng($source);
    }
    imagejpeg($image, $destination, $quality);
    return $destination;
}

function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
    $srcWidth = imagesx($img);
    $srcHeight = imagesy($img);
    $srcRatio = $srcWidth / $srcHeight;
    $targetRatio = $targetWidth / $targetHeight;
    if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight)) {
        $imgTargetWidth = $srcWidth;
        $imgTargetHeight = $srcHeight;
    } else if ($targetRatio > $srcRatio) {
        $imgTargetWidth = (int) ($targetHeight * $srcRatio);
        $imgTargetHeight = $targetHeight;
    } else {
        $imgTargetWidth = $targetWidth;
        $imgTargetHeight = (int) ($targetWidth / $srcRatio);
    }
    $targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
    $targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
    imagefill($targetImg, 0, 0, $targetTransparent);
    imagecolortransparent($targetImg, $targetTransparent);
    imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);
    return $targetImg;
}
?>
Run Code Online (Sandbox Code Playgroud)

小智 3

我使用作者描述的方法成功地使其工作,但我使用的fetch()是而不是 jQuery:

document.forms[0].addEventListener("submit", async function (e) {
    e.preventDefault();
    const url = this.getAttribute("action"); // grab endpoint from HTML
    const fd = new FormData();   // create FormData object
    upload.cachedFileArray.forEach((file, i) => {
        fd.append("files[]", file); // append each file to FormData object
    });
    this.querySelectorAll("input[name], select, textarea").forEach(el => {
        fd.append(el.getAttribute("name"), el.value);
    });
    const response = await fetch(url, {
        method: 'POST',
        body: fd
    });
    // optional processing of server response
    const text = await response.text();
    console.log('Success:', text);
    // what happens after upload here
    location = "https://google.com"; // navigate to Google
});
Run Code Online (Sandbox Code Playgroud)

将其添加到您的脚本中。它拦截表单提交,FormData根据 File 数组创建一个对象,添加剩余的表单字段,然后将其提交到指定表单action属性的 url。请注意,您可能应该name<input type="file">表单上删除该属性,因为我们不想将其添加到 FormData 中。