问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Vue图片上传那些坑,你踩过几个?

创作时间:
作者:
@小白创作中心

Vue图片上传那些坑,你踩过几个?

引用
CSDN
12
来源
1.
https://blog.csdn.net/m0_63586335/article/details/140613344
2.
https://blog.csdn.net/weixin_45356258/article/details/139352946
3.
https://blog.csdn.net/m0_66879773/article/details/136732038
4.
https://blog.csdn.net/torpidcat/article/details/140131206
5.
https://blog.csdn.net/weixin_47597807/article/details/119361697
6.
https://blog.csdn.net/m0_54195598/article/details/143975166
7.
https://blog.csdn.net/sinat_41200024/article/details/139298793
8.
https://cloud.baidu.com/article/3236059
9.
https://blog.csdn.net/qq_39291270/article/details/143587598
10.
https://www.showapi.com/news/article/67027ef64ddd79f11a32ea3e
11.
https://juejin.cn/post/7402845471646285864
12.
https://docs.pingcode.com/baike/2331190

在Vue项目中处理图片上传功能时,开发者经常会遇到一些令人头疼的技术问题。本文将分享几个常见的坑点及解决方案,帮助大家在开发过程中少走弯路。

01

图片更新后不显示新图片

现象描述

在更新用户头像或图片后,页面上显示的仍然是旧图片,即使后端已经成功返回新的图片URL。

原因分析

这是因为浏览器对图片进行了缓存,即使图片URL发生变化,浏览器也可能加载缓存中的旧图片。Vue并未检测到变化,导致页面头像没有发生改变。

解决方案

在图片URL后拼接时间戳,强制浏览器加载最新图片。以下是两种实现方式:

  1. 在模板中直接拼接时间戳:
<img :src="imageUrl ? imageUrl+ '?t=' + (new Date().getTime()) : ''" />
  1. 在获取新图片地址时拼接时间戳:
const { Data } = await UploadImg(infoData.dialog!.params.RY_GH, formData);
imageUrl.value = common.baseUrl + Data.URL+'?t=' + (new Date().getTime());
02

跨域上传导致请求失败

现象描述

当使用Vue前端上传图片到后端服务器时,可能会遇到跨域问题,导致上传请求被浏览器阻止。

原因分析

跨域问题通常发生在前端和后端部署在不同域名或端口的情况下。浏览器的同源策略会阻止跨域请求,除非后端明确允许。

解决方案

使用axios进行文件上传时,需要正确设置请求头。以下是一个完整的跨域上传示例:

<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action=""
      :http-request="uploadFile1"
      list-type="picture"
      :show-file-list="false"
    >
      <img v-if="imageUrl" class="avatar" :src="imageUrl" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";

const imageUrl = ref("");
const uploadFile1 = async (val: any) => {
  let formdata = new FormData();
  formdata.append("File", val.file);

  await axios.post("http://192.168.1.214:5050/api/File/UploadFile", formdata, {
    headers: { "Content-Type": "multipart/form-data" },
  }).then((res) => {
    if (res.data.status === 200) {
      // 获取文件路径并显示图片
      axios.post("http://192.168.1.214:5050/api/File/FilePathInfo", {
        id: res.data.data.id,
      }).then((result) => {
        imageUrl.value = "http://192.168.1.214:5050" + result.data.data.filePath;
      });
    }
  });
};
</script>
03

文件大小限制检查

现象描述

在上传图片时,如果用户选择的文件过大,需要及时给出提示并阻止上传。

解决方案

使用elementPlus的upload组件时,可以通过on-change事件来检查文件大小:

<el-upload
  v-model:file-list="item.fileList"
  accept=".jpg,.jpeg,.png,.gif,.webp"
  list-type="picture-card"
  :on-change="handleSuccess"
  :limit="imgLength"
  :auto-upload="false"
>
  <el-icon>
    <Plus />
  </el-icon>
</el-upload>

在on-change事件中检查文件大小:

const handleSuccess = (file: UploadFile) => {
  const maxSize = 30 * 1024 * 1024; // 限制30M
  if (file.size > maxSize) {
    ElMessage.warning('文件大小不得超过30M');
    fileList.value = [];
    return;
  }
  // 其他逻辑
}
04

上传进度显示

现象描述

在上传大文件时,用户需要看到上传进度,避免误以为程序卡死而重复点击上传按钮。

解决方案

利用HTML5的progress标签和axios的onUploadProgress事件,可以实现上传进度条:

// 封装上传图片接口方法
export const uploadCourseImage = (data, onUploadProgress) => {
  return request({
    method: 'POST',
    url: '',
    data,
    onUploadProgress
  })
}

// 在Vue组件中调用
const { data } = await uploadCourseImage(fd, e => {
  this.percentage = Math.floor(e.loaded / e.total * 100)
})

在模板中使用element ui的进度条组件:

<el-progress
  v-if="isUploading"
  :percentage="percentage"
  status="success"
></el-progress>

通过以上几个解决方案,可以有效提升Vue项目中图片上传功能的用户体验。在实际开发中,建议将这些功能模块化,以便在多个项目中复用。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号