实现多张图片拖拽上传并可以拖拽调整图片顺序的示例代码:
<template>
<div>
<el-upload
ref="uploadRef"
class="upload-demo"
drag
action="#"
:auto-upload="false"
:on-change="handleChange"
multiple
>
<el-icon class="el-icon--upload"><upload-filled /></el-icon>
<div class="el-upload__text">
Drop file here or <em>click to upload</em>
</div>
</el-upload>
<div class="image-list" ref="imageListRef">
<div
v-for="(image, index) in images"
:key="index"
class="image-item"
draggable="true"
@dragstart="dragStart(index)"
@dragover.prevent
@dragenter.prevent
@drop="drop(index)"
>
<el-image :src="image.url" fit="cover" />
<el-button type="danger" size="small" @click="removeImage(index)">
Remove
</el-button>
</div>
</div>
<el-button type="primary" @click="uploadImages">Upload Images</el-button>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import axios from 'axios'
interface ImageItem {
file: File
url: string
}
const uploadRef = ref()
const imageListRef = ref()
const images = ref<ImageItem[]>([])
let dragIndex = -1
const handleChange = (file: any) => {
const reader = new FileReader()
reader.onload = (e) => {
images.value.push({
file: file.raw,
url: e.target?.result as string,
})
}
reader.readAsDataURL(file.raw)
}
const removeImage = (index: number) => {
images.value.splice(index, 1)
}
const dragStart = (index: number) => {
dragIndex = index
}
const drop = (index: number) => {
if (dragIndex !== index) {
const temp = images.value[dragIndex]
images.value.splice(dragIndex, 1)
images.value.splice(index, 0, temp)
}
}
const uploadImages = async () => {
const formData = new FormData()
images.value.forEach((image, index) => {
formData.append(`image${index}`, image.file)
})
try {
const response = await axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
ElMessage.success('Images uploaded successfully')
console.log(response.data)
} catch (error) {
ElMessage.error('Failed to upload images')
console.error(error)
}
}
</script>
<style scoped>
.image-list {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 20px;
}
.image-item {
width: 150px;
text-align: center;
}
.el-image {
width: 100%;
height: 150px;
margin-bottom: 10px;
}
</style>
这个示例实现了以下功能:
- 使用 Element Plus 的
el-upload
组件实现拖拽上传。 - 支持多文件上传。
- 上传的图片会显示在下方的图片列表中。
- 可以拖拽调整图片的顺序。
- 可以删除已上传的图片。
- 点击 “Upload Images” 按钮会将所有图片上传到服务器。
注意事项:
- 这个示例使用了客户端预览,实际图片数据还是存储在
File
对象中。 - 服务器端需要相应地处理多文件上传请求。
- 可以根据需要调整样式和布局。
- 记得处理可能的错误情况和添加适当的验证。
关注微信公众号温暖前端,不定期分享前端知识点和前端资料↓↓↓
标签:index,const,image,value,file,images,上传,拖拽,图片 From: https://blog.csdn.net/qq_45914628/article/details/141232366