backend/docs/调用图片上传组件.md
2026-01-26 09:32:17 +08:00

90 lines
2.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<el-form-item label="默认图片" prop="image">
<div class="uploads">
<el-upload v-model:file-list="fileList" :action="uploadUrl" list-type="picture-card" :headers="uploadHeaders"
:limit="1" :auto-upload="false" :before-upload="beforeImgUpload" :on-success="handleImgSuccess">
<el-icon>
<Plus />
</el-icon>
<template #file="{ file }">
<div>
<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
<span class="el-upload-list__item-actions">
<span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
<el-icon>
<ZoomIn />
</el-icon>
</span>
<span class="el-upload-list__item-delete" @click="handleRemove(file)">
<el-icon>
<Delete />
</el-icon>
</span>
</span>
</div>
</template>
</el-upload>
<el-dialog v-model="dialogVisible">
<img w-full :src="dialogImageUrl" alt="Preview Image" />
</el-dialog>
<div class="upload-tip">
<span>建议尺寸250px × 140px</span>
</div>
</div>
</el-form-item>
import { uploadFile } from '@/api/file.js';
import { ElMessage, ElUpload } from 'element-plus'
// 上传相关
const fileList = ref<any[]>([])
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
function beforeImgUpload(file: File) {
const isImage = file.type.startsWith('image/')
const isLt10M = file.size / 1024 / 1024 < 10
if (!isImage) ElMessage.error('仅支持图片格式')
if (!isLt10M) ElMessage.error('图片大小不能超过10MB')
return isImage && isLt10M
}
function handleImgUpload(file: File) {
const formData = new FormData()
formData.append('file', file)
formData.append('cate', 'article')
uploadFile(formData).then((res: any) => {
if (res?.url) {
formData.image = res.url
fileList.value = [{
name: file.name,
url: res.url
}]
}
}).catch((error: any) => {
ElMessage.error('上传失败:' + (error.msg || '未知错误'))
})
}
function handlePictureCardPreview(file: any) {
dialogImageUrl.value = file.url
dialogVisible.value = true
}
function handleRemove(file: any) {
fileList.value = []
formData.image = ''
}
.uploads{
display: flex;
flex-direction: column;
}
.upload-tip {
font-size: 12px;
color: #999;
}