解决 Vue.js 上传组件中图片路径 Blob 前缀问题

在使用 Vue.js 上传组件,例如 Element UI 的 el-upload 时,你可能会遇到图片路径带有 'blob:' 前缀的问题。这通常是因为浏览器使用 URL.createObjectURL() 方法生成临时 URL 导致的。

如何去除 'blob:' 前缀?

你可以通过设置 beforeUpload 函数来修改上传的文件名或路径,在该函数中对文件名或路径进行处理,去掉前缀。

代码示例:

<template>
  <el-upload
    class='upload-demo'
    action='/upload'
    :before-upload='handleBeforeUpload'
    :on-success='handleSuccess'
    :on-error='handleError'
    :file-list='fileList'
    multiple>
    <el-button size='small' type='primary'>点击上传</el-button>
  </el-upload>
</template>

<script>
export default {
  data() {
    return {
      fileList: []
    }
  },
  methods: {
    handleBeforeUpload(file) {
      // 去掉blob前缀
      const url = URL.createObjectURL(file)
      const fileName = file.name
      const newFileName = fileName.replace(/^blob:/, '')
      const newUrl = url.replace(/^blob:/, '')
      // 修改上传的文件名或路径
      file.url = newUrl
      file.name = newFileName
      return true
    },
    handleSuccess(response, file, fileList) {
      console.log(response)
      console.log(file)
      console.log(fileList)
    },
    handleError(error, file, fileList) {
      console.log(error)
      console.log(file)
      console.log(fileList)
    }
  }
}
</script>

代码解释:

  1. handleBeforeUpload 函数:
    • 使用 URL.createObjectURL(file) 获取文件的 URL。
    • 使用 replace(/^blob:/, '') 正则表达式去除 URL 和文件名中的 'blob:' 前缀。
    • 将修改后的 URL 和文件名分别赋值给 file.urlfile.name
  2. return true: 确保上传流程继续执行。

通过以上步骤,你就可以在 Vue.js 上传组件中成功去除图片路径的 'blob:' 前缀,并进行正常的图片上传操作。

Vue.js 上传组件中去除图片路径 Blob 前缀

原文地址: https://www.cveoy.top/t/topic/jSqr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录