该工具支持上传图片、删除图片,添加了一个input输入框,所有上传的图片自动更新到Input,添加、删除的图片也会更新到input框,这个Input可以放到form中,把数据提交到后台。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dropzone.js 图片管理示例</title>
<!-- Dropzone CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.min.css" rel="stylesheet">
<style>
#image-list img {
max-width: 200px;
height: 100px;
margin: 10px;
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
}
.dropzone {
border: 2px dashed #0087F7;
border-radius: 5px;
background: white;
padding: 20px;
margin-bottom: 20px;
}
</style>
</head>
<body>
<h1>Dropzone.js 图片管理示例</h1>
<!-- 上传区域 -->
<div id="dropzone-area" class="dropzone" style="display: inline-block;"></div>
<!-- 图片展示区域 -->
<div id="image-list" style="display: inline-block;">
<h2>图片展示</h2>
</div>
<!-- 图片地址存储 -->
<input type="text" id="image-urls" style="width: 100%; margin-bottom: 20px;" readonly>
<!-- Dropzone JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.min.js"></script>
<script>
// 图片上传控件
const myDropzone = new Dropzone("#dropzone-area", {
url: "/upload/image", // 上传接口地址
paramName: "file", // 文件字段名
maxFilesize: 5, // 文件大小限制(MB)
acceptedFiles: "image/*", // 只允许上传图片
maxFiles: 1, // 最多上传 10 个文件
dictDefaultMessage: "将文件拖放到此处或点击上传", // 设置提示内容为中文
init: function () {
this.on("success", function (file, response) {
// 解析返回的图片地址
let data = JSON.parse(response);
const imgUrl = data.data.img;
// 将图片地址添加到 input 中
addImageUrl(imgUrl);
// 刷新图片展示
renderImages();
// 移除 Dropzone 中的文件,以便可以继续上传
this.removeFile(file);
});
}
});
// 获取 input 元素
const imageUrlsInput = document.getElementById('image-urls');
// 添加图片地址到 input
function addImageUrl(imgUrl) {
let urls = imageUrlsInput.value ? imageUrlsInput.value.split(',') : [];
urls.push(imgUrl);
imageUrlsInput.value = urls.join(',');
}
// 从 input 中移除图片地址
function removeImageUrl(imgUrl) {
let urls = imageUrlsInput.value ? imageUrlsInput.value.split(',') : [];
urls = urls.filter(url => url !== imgUrl);
imageUrlsInput.value = urls.join(',');
}
// 渲染图片展示
function renderImages() {
const imageList = document.getElementById('image-list');
imageList.innerHTML = '<h2></h2>'; // 清空现有内容
const urls = imageUrlsInput.value ? imageUrlsInput.value.split(',') : [];
urls.forEach(imgUrl => {
const imageItem = document.createElement('span');
imageItem.className = 'image-item';
const imgElement = document.createElement('img');
imgElement.src = imgUrl;
const deleteBtn = document.createElement('button');
deleteBtn.type = 'button';
deleteBtn.className = 'delete-btn';
deleteBtn.innerHTML = '×';
deleteBtn.onclick = function () {
removeImageUrl(imgUrl); // 从 input 中移除图片地址
renderImages(); // 重新渲染图片展示
};
imageItem.appendChild(imgElement);
imageItem.appendChild(deleteBtn);
imageList.appendChild(imageItem);
});
}
// 页面加载时,初始化图片展示
renderImages();
</script>
</body>
</html>
展示效果如下:

1626

被折叠的 条评论
为什么被折叠?



