gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:02:50 28 4
gpt4 key购买 nike

我用 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',
},
});
.custom-file-container {
max-width: 400px;
margin: 0 auto;
}
<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>


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

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;
}
?>

最佳答案

我使用作者描述的方法成功地让它工作,但我使用的是 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
});

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

关于javascript - 无法从多个 html 输入字段中添加或删除图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59195429/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com