上传upload及显示img图片预览、删除

本文介绍了在Vue项目中使用anti-design-vue和elementui组件进行图片上传、预览和删除的功能实现。详细讲解了HTML、JS和CSS代码部分,并提供了antd和element两种预览方式。示例中展示了如何通过v-model绑定文件列表,回显已上传图片,以及如何添加图片预览和删除功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上传图片文件a-upload

html部分

 <div className="clearfix">
  <a-upload
      :custom-request="customRequest"
      listType="picture-card"
      :fileList="fileList"
      :onPreview="handlePreview"
      :on-remove="del"
  >
    <div>
      <plus-outlined/>
      <div className="ant-upload-text">Upload</div>
    </div>
  </a-upload>
  <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
    <img alt="" style="width: 100%" :src="previewImage"/>
  </a-modal>
</div> 

js部分

// 是否预览
const previewVisible = ref(false)
// 图片url
const previewImage = ref('')
// 图片集合
const fileList = ref([])
// 图片id
const currentfileId = ref()

const handleCancel = () => {
   
  console.log("关闭预览图")
  previewVisible.value = false
}

const handlePreview = (file) => {
   
  console.log("预览操作")
  previewImage.value = file.url || file.thumbUrl
  previewVisible.value = true
}

const customRequest = async ({
    
                               action,
                               data,
                               file,
                               filename,
                               headers,
                               onError,
                               onProgress,
                               onSuccess,
                               withCredentials
                             }) => {
   
  const formData = new FormData()
  formData.append('file', file)
  const fileId = await fileApi.fileUploadDynamicReturnId(formData)
  emit('uploadDone', fileId)
  onSuccess({
   data: fileId}, file)
  // 加入到显示集合,此处直接赋值,因为我设置的只能有一张图,fileList为数组[],file为对象{}
  fileList.value = [file]
  currentfileId.value = fileId
}

const del = (file) => {
   
  fileApi.fileDelete([{
    id: currentfileId.value }]).then((res) => {
   
    // 同时清空 fileList
    fileList.value = []
    currentfileId.value = ''
  })
}

css部分

 .ant-upload-select-picture-card i {
   
  font-size: 28px;
  color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
   
  margin-top: 8px;
  font-size: 12px;
  color: #666;
} 

效果图:

未上传图片上传了一张图片

参考

以上是参考官方文档antd(2.13.11),该组件文档如下:

import {
    Upload, Icon, Modal } from 'antd';
class PicturesWall extends React.Component {
   
	state = {
   
		previewVisible: false,
		previewImage: '',
		f
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值