vue3+ts el-upload

文章介绍了如何在Vue项目中使用ElementPlus的el-upload组件实现文件上传功能,包括文件拖拽、上传限制、删除和预览操作,以及与axios的集成以进行HTTP请求。
摘要由CSDN通过智能技术生成

vue文件

<template>
  <div>
    <el-upload
      ref="upload"
      class="upload-demo"
      drag
      multiple
      action=""
      :disabled="disabled"
      :auto-upload="true"
      :limit="10"
      :before-remove="beforeRemoveFn"
      :on-preview="handlePreviewFn"
      :on-exceed="handleExceedFn"
      :file-list="fileList"
      :http-request="uploadFileFn"
    >
      <div v-if="!disabled">
        <div class="container">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖到此处,或<br /><em>点击上传</em></div>
        </div>
        <p class="el-upload__tip">1.最多可上传10个附件,附件大小不得超过8M;</p>
      </div>
      <div v-else>
        <p>不可以上传附件或删除附件</p>
      </div>
    </el-upload>
  </div>
</template>
<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { deleteAttachmentAPI, downloadAPI, uploadFilesAPI } from './jiekou'

const disabled = ref(false)
const fileList = ref<any>([])

// 删除上传文件
const beforeRemoveFn = (file: any) => {
  const { id } = file
  deleteAttachmentAPI({ id }).then(() => {
    ElMessage({ type: 'success', message: '删除成功' })
  })
}
// 下载文件
const handlePreviewFn = (file: any) => {
  if (file.url) downloadAPI(file.id)
}
// 选取文件超过数量提示
const handleExceedFn = () => {
  ElMessage({ type: 'error', message: '最多支持10个附件上传' })
}
// 上传文件
const uploadFileFn = (val: any) => {
  const formData = new FormData()
  formData.append('files', val.file)
  formData.append('category', 'imp')
  uploadFilesAPI(formData).then((res: any) => {
    res.data.forEach((item: any) =>
      fileList.value.push({
        name: item.attachmentName,
        url: item.attachmentPath,
        id: item.attachmentId,
      })
    )
  })
}
</script>
<style lang="scss" scoped>
.upload-demo {
  ::v-deep .el-upload-dragger {
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 619px;
    height: 84px;
    line-height: 17px;
    border: 1px solid #d0d2d7;

    .container {
      display: flex;
      align-items: center;
    }

    .el-upload__text {
      font-size: 12px;
      text-align: start;
    }

    i {
      margin: 0 5px 0;
      font-size: 20px;
    }
  }
}
</style>

axios文件

import axios from 'axios'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'

export interface HttpResponse<T = unknown> {
  status: number
  msg: string
  code: number
  data: T
}
export function get<T = any>(url: string, params?: any, config?: AxiosRequestConfig) {
  return axios
    .get<HttpResponse<T>>(url, {
      ...config,
      params,
    })
    .then((respose) => {
      return respose.data.data
    })
}

export function post<T = any, D = any>(url: string, data?: D, config?: AxiosRequestConfig) {
  return axios.post<HttpResponse<T>>(url, data, config).then((respose) => {
    return respose.data.data
  })
}
export function del<T = any>(url: string, config?: AxiosRequestConfig) {
  return axios.delete<HttpResponse<T>>(url, config).then((respose) => {
    return respose.data.data
  })
}

const handelBlobResponse = (response: AxiosResponse<Blob, any>) => {
  const href = URL.createObjectURL(response.data)
  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = href
  let filename = ''
  const content = response.headers['content-disposition'] // 注意是全小写,自定义的header也是全小写
  if (content) {
    const name = content.match(/filename=(.*)/)![1]
    filename = decodeURIComponent(name)
  }
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

export function download(url: string, params?: any, config?: any) {
  return axios
    .get<Blob>(url, {
      ...config,
      params,
      responseType: 'blob',
    })
    .then(handelBlobResponse)
    .catch((err) => {
      console.error(err)
    })
}

export function postDownload(url: string, data?: any, config?: any) {
  return axios.post<Blob>(url, data, {
    ...config,
    // responseType: 'blob',
  })
  // .then(handelBlobResponse)
}

以下是使用Vue3和TypeScript结合Element-Plus实现头像上传的示例代码: ```vue <template> <div> <el-upload class="avatar-uploader" action="/upload" :show-file-list="false" :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError" > <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue'; export default defineComponent({ name: 'AvatarUploader', setup() { const imageUrl = ref(''); const beforeUpload = (file: File) => { // 验证文件类型和大小等 return true; }; const handleSuccess = (response: any) => { // 上传成功后的处理逻辑 imageUrl.value = response.data.url; }; const handleError = (error: any) => { // 上传失败后的处理逻辑 console.log(error); }; return { imageUrl, beforeUpload, handleSuccess, handleError, }; }, }); </script> <style scoped> .avatar-uploader { display: inline-block; width: 100px; height: 100px; border-radius: 50%; overflow: hidden; background: #f8f8f8; position: relative; cursor: pointer; } .avatar { width: 100%; height: 100%; object-fit: cover; } .avatar-uploader-icon { font-size: 28px; color: #8c939d; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> ``` 这是一个名为`AvatarUploader`的Vue组件,使用了`el-upload`组件来实现头像上传功能。在`beforeUpload`方法中,你可以添加文件类型和大小的验证逻辑。在`handleSuccess`方法中,你可以处理上传成功后的逻辑,例如更新头像的URL。在`handleError`方法中,你可以处理上传失败后的逻辑。 你可以将以上代码保存为一个.vue文件,然后在你的Vue项目中使用该组件来实现头像上传功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值