antd upload组件编辑时显示已有图片

771 阅读1分钟

需求:页面有新增和编辑功能,新增时,upload显示上传图片按钮,编辑时,除了上传图片按钮,还有已有的图片显示

新增时,只显示上传按钮

截屏2022-05-06 上午10.17.03.png

编辑时,显示按钮和现有头像 截屏2022-05-06 上午10.18.20.png

<a-form-item label="头像" required>
   <a-upload
     v-model:file-list="fileListAvatar"
     name="file"
     action="/fitlive/eunomia/file/coach/photo?type=1"
     list-type="picture"
     :headers="uploadFileHeaders"
     :multiple="false"
     @change="handleUploadChangeAvatarUrl">
        <a-button :loading="uploadingMD5" id="uploadAvatar">上传头像</a-button>
    </a-upload>
</a-form-item>

。。。。。。

<TableAction
    :actions="[{
         label: '编辑',
         onClick: showUpdateForm.bind(null, record),
     }]"
/>

此时注意:fileListAvatar的value值结构为 (官网例子)
{ 
    uid: '-1', 
    name: 'xxx.png', 
    status: 'done', 
    url:'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', 
    thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', 
},


function showUpdateForm(record) {
        modalVisible.value = true;  //显示编辑弹窗
        。。。。。。
        fileListAvatar.value = fileListFormate(record.avatarUrl,'-1') //调用fileListFormate方法,获取fileListAvatar.value
        formState.avatarUrl = record.avatarUrl; //原来的数据,如果没有修改,则保持不变,若是修改,在handleUploadChangeAvatarUrl中进行更新
        。。。。。。
      }
      
function fileListFormate(url,uid){
   if(url){
      return [{
          uid: uid,
          status: 'done',
          url: url,
          thumbUrl: url,
      }]
  }else {
     return []
  }  
}
const handleUploadChangeAvatarUrl = (info) => {
    try {
       if (info.file.status === 'done') {
          //编辑时,因为头像已经有一张照片了,所以fileListAvatar.value.length为1,
          //当fileListAvatar.value.length > 1时,说明更新了头像照片,会在fileListAvatar.value从数组后面加入照片信息
          //那么,当fileListAvatar.value.length大于1时,就从数组前删除照片信息,由此更新时显示的就是最新照片
          fileListAvatar.value.length > 1 ? fileListAvatar.value.shift() : ''
          //在form表单更新最新的头像信息
          formState.avatarUrl = info.file.response.result.fileUrl;      
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} file upload failed.`);
        }
    } catch (error) {
         console.log(error);
    }
};