Vue el-upload单图片上传功能实现

 更新时间:2023年11月25日 10:42:15   作者:爱学习的疯倾  
这篇文章主要介绍了Vue el-upload单图片上传功能实现,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一、前端相关:

<!--:action里面放图片上传调取的后台方法 :headers设置上传的请求头部,使请求携带自定义token,获取访问权限 -->
<!--:on-success图片上传成功后的回调方法,用于拿到图片存储路径等信息-->
<!--:before-upload图片上传前的逻辑判断,例如判断图片大小,格式等-->
<!--:on-preview图片预览方法 :on-remove图片删除方法 list-type代表文件列表的类型 -->
<!--file-list存放成功上传图片列表,这里此属性用于修改功能时页面已有图片的显示-->
<el-form-item label="预览缩略图" prop="articleImg" label-width="40">
              <el-upload
                :action="imgUpload.url"
                :headers="imgUpload.headers"
                list-type="picture-card"
                :limit="limit"
                :on-exceed="handleExceed"
                :on-success="handlePictureSuccess"
                :before-upload="beforeAvatarUpload"
                :on-preview="handlePictureCardPreview"
                :file-list="fileList"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" v-if="imageUrl" :src="imageUrl" alt="">
              </el-dialog>
            </el-form-item>

二、属性值方法的定义: 

export default {
  name: "Article",
  data() {
    return {
    // 图片数量限制
    limit: 1,
    //页面上存的暂时图片地址List
      fileList: [{url: ""}],
    //图片地址
      imageUrl: "",
      dialogVisible: false,
      imgUpload: {
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 图片上传的方法地址:
          url: process.env.VUE_APP_BASE_API + "/forum/forum/multiPicturesUpload",
      }
    };
},
methods: {
// 表单重置
 reset()
{  ...... 忽略其它
  this.fileList = undefined;  this.resetForm("form");
}
/** 修改按钮操作 */
handleUpdate(row) {
  this.reset();
  this.getTreeSelect();
  const articleId = row.articleId || this.ids;
  getArticle(articleId).then(response => {
    this.fileList = [{ url: process.env.VUE_APP_BASE_API + response.data.articleImg}]   this.form = response.data;
    this.open = true;
    this.title = "修改文章";
  });
},
/** 提交按钮 */
submitForm: function() {
  this.form.articleImg = this.imageUrl; // 注:重要(用于添加到数据库)
  this.$refs["form"].validate(valid => {
    if (valid) {
      if (this.form.articleId != undefined) {
        updateArticle(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addArticle(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    }
  });
},
//图片上传前的相关判断
beforeAvatarUpload(file) {
  const isJPG = file.type === 'image/jpeg' || file.type == 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 5;
  if (!isJPG) {
    this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    this.$message.error('上传头像图片大小不能超过 5MB!');
  }
  return isJPG && isLt2M;
},
//图片预览
handlePictureCardPreview(file) {
  this.imageUrl = file.url;
  this.dialogVisible = true;
},
//图片上传成功后的回调
handlePictureSuccess(res, file) {
  //设置图片访问路径 (articleImg 后台传过来的的上传地址)
  this.imageUrl = file.response.articleImg;
},
// 文件个数超出
handleExceed() {
  this.$modal.msgError(`上传链接LOGO图片数量不能超过 ${this.limit} 个!`);
},
}
};
export default {
  name: "Article",
  data() {
    return {
    // 图片数量限制
    limit: 1,
    //页面上存的暂时图片地址List
      fileList: [{url: ""}],
    //图片地址
      imageUrl: "",
      dialogVisible: false,
      imgUpload: {
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 图片上传的方法地址:
          url: process.env.VUE_APP_BASE_API + "/forum/forum/multiPicturesUpload",
      }
    };
},
methods: {
// 表单重置
 reset()
{  ...... 忽略其它
  this.fileList = undefined;  this.resetForm("form");
}
/** 修改按钮操作 */
handleUpdate(row) {
  this.reset();
  this.getTreeSelect();
  const articleId = row.articleId || this.ids;
  getArticle(articleId).then(response => {
    this.fileList = [{ url: process.env.VUE_APP_BASE_API + response.data.articleImg}]   this.form = response.data;
    this.open = true;
    this.title = "修改文章";
  });
},
/** 提交按钮 */
submitForm: function() {
  this.form.articleImg = this.imageUrl; // 注:重要(用于添加到数据库)
  this.$refs["form"].validate(valid => {
    if (valid) {
      if (this.form.articleId != undefined) {
        updateArticle(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addArticle(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    }
  });
},
//图片上传前的相关判断
beforeAvatarUpload(file) {
  const isJPG = file.type === 'image/jpeg' || file.type == 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 5;
  if (!isJPG) {
    this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    this.$message.error('上传头像图片大小不能超过 5MB!');
  }
  return isJPG && isLt2M;
},
//图片预览
handlePictureCardPreview(file) {
  this.imageUrl = file.url;
  this.dialogVisible = true;
},
//图片上传成功后的回调
handlePictureSuccess(res, file) {
  //设置图片访问路径 (articleImg 后台传过来的的上传地址)
  this.imageUrl = file.response.articleImg;
},
// 文件个数超出
handleExceed() {
  this.$modal.msgError(`上传链接LOGO图片数量不能超过 ${this.limit} 个!`);
},
}
};

注:在提交事件中添加:this.form.articleImg = this.imageUrl;

三、效果如下:

四、后台上传图片方法代码:

注:articleImg传给了前端 handlePictureSuccess回调方法中

/**
     * 缩略图上传
     */
    @Log(title = "预览缩略图", businessType = BusinessType.UPDATE)
    @PostMapping("/articleImg")
    public AjaxResult uploadFile(MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            String articleImg = FileUploadUtils.upload(RuoYiConfig.getArticleImgPath(), file);
            if (!StringUtils.isEmpty(articleImg))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("articleImg", articleImg);
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常,请联系管理员");
    }

1、文件上传工具类:FileUploadUtils

/**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file) throws IOException
    {
        try
        {
            return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        }
        catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }

2、读取项目相关配置:RuoYiConfig

package com.ruoyi.common.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
 * 读取项目相关配置
 * 
 * @author ruoyi
 */
@Component
@ConfigurationProperties(prefix = "ruoyi")
public class RuoYiConfig
{/** 上传路径 */
    private static String profile;
public static String getProfile()
    {
        return profile;
    }
    public void setProfile(String profile)
    {
        RuoYiConfig.profile = profile;
    }
/**
     * 获取导入上传路径
     */
    public static String getImportPath()
    {
        return getProfile() + "/import";
    }/**
     * 获取预览缩略图上传路径
     * @return
     */
    public static String getArticleImgPath()
    {
        return getProfile() + "/articleImg";
    }
    /**
     * 获取下载路径
     */
    public static String getDownloadPath()
    {
        return getProfile() + "/download/";
    }
    /**
     * 获取上传路径
     */
    public static String getUploadPath()
    {
        return getProfile() + "/upload";
    }
}

到此这篇关于Vue el-upload单图片上传的文章就介绍到这了,更多相关Vue el-upload单图片上传内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • vue路由相对路径跳转方式

    vue路由相对路径跳转方式

    这篇文章主要介绍了vue路由相对路径跳转方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08
  • 详解element-ui中el-select的默认选择项问题

    详解element-ui中el-select的默认选择项问题

    这篇文章主要介绍了详解element-ui中el-select的默认选择项问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08
  • vue实现学生录入系统之添加删除功能

    vue实现学生录入系统之添加删除功能

    本文给大家带来一个小案例基于vue实现学生录入系统功能,代码简单易懂非常不错,具有一定的参考借鉴价值,需要的朋友参考下吧
    2018-07-07
  • Vue路由守卫详解

    Vue路由守卫详解

    路由导航守卫提供了一些钩子函数,可以在路由导航过程中进行拦截和控制,其中,beforeEach 导航守卫可以在每次路由切换前被触发,本文给大家介绍Vue路由守卫详解,感兴趣的朋友一起看看吧
    2023-10-10
  • 基于vue3&element-plus的暗黑模式实例详解

    基于vue3&element-plus的暗黑模式实例详解

    实现暗黑主题的方式有很多种,也有很多成型的框架可以直接使用,下面这篇文章主要给大家介绍了关于基于vue3&element-plus的暗黑模式的相关资料,需要的朋友可以参考下
    2022-12-12
  • vue实现双向数据绑定

    vue实现双向数据绑定

    这篇文章主要为大家详细介绍了vue实现双向数据绑定,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-05-05
  • VUE实现强制渲染,强制更新

    VUE实现强制渲染,强制更新

    今天小编就为大家分享一篇VUE实现强制渲染,强制更新,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-10-10
  • Vue.js 父子组件通信的十种方式

    Vue.js 父子组件通信的十种方式

    最近一直在做 Vue项目代码层面上的优化,写文章是很easy的事情,今天小编给大家分享Vue.js 父子组件通信的十种方式,感兴趣的的朋友跟随小编一起看看吧
    2018-10-10
  • vue+elementUI用户修改密码的前端验证规则

    vue+elementUI用户修改密码的前端验证规则

    用户登录后修改密码,密码需要一定的验证规则,这篇文章主要介绍了vue+elementUI用户修改密码的前端验证,需要的朋友可以参考下
    2024-03-03
  • 超全面的vue.js使用总结

    超全面的vue.js使用总结

    Vue.js是当下很火的一个JavaScript MVVM库,它是以数据驱动和组件化的思想构建的。相比于Angular.js,Vue.js提供了更加简洁、更易于理解的API,使得我们能够快速地上手并使用Vue.js。下面这篇文章主要给大家介绍了关于vue.js使用的相关总结,需要的朋友可以参考借鉴。
    2017-02-02

最新评论