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中路由跳转的多种方式(和$router下路由跳转的那几个方法的区别)

    vue中路由跳转的多种方式(和$router下路由跳转的那几个方法的区别)

    Vue.js是一款流行的前端JavaScript框架,它提供了多种方式来实现路由跳转,本文给大家分享vue中路由跳转的几种方式(和$router下路由跳转的那几个方法的区别),感兴趣的朋友一起看看吧
    2023-11-11
  • vue3.0+element表格获取每行数据代码示例

    vue3.0+element表格获取每行数据代码示例

    这篇文章主要给大家介绍了关于vue3.0+element表格获取每行数据的相关资料,在element-ui中,你可以通过为表格的行绑定单击事件来获取表格中的一行数据,需要的朋友可以参考下
    2023-09-09
  • 如何利用vue-cli监测webpack打包与启动时长

    如何利用vue-cli监测webpack打包与启动时长

    这篇文章主要给大家介绍了关于如何利用vue-cli监测webpack打包与启动时长的相关资料,文中通过实例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2022-02-02
  • 详解vue-cli@2.x项目迁移日志

    详解vue-cli@2.x项目迁移日志

    这篇文章主要介绍了详解vue-cli@2.x项目迁移日志,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-06-06
  • vue同一浏览器登录多账号处理方案

    vue同一浏览器登录多账号处理方案

    项目在线上会遇到管理员类似权限比较大的用户,会在同一浏览器登陆多个账号,遇到这样的问题如何处理呢,下面小编给大家介绍vue同一浏览器登录多账号处理方法,感兴趣的朋友一起看看吧
    2024-01-01
  • Vue element-ui父组件控制子组件的表单校验操作

    Vue element-ui父组件控制子组件的表单校验操作

    这篇文章主要介绍了Vue element-ui父组件控制子组件的表单校验操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-07-07
  • Vue3使用src动态引入本地图片的详细步骤

    Vue3使用src动态引入本地图片的详细步骤

    这篇文章主要给大家介绍了关于Vue3使用src动态引入本地图片的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2022-12-12
  • Vue中EpicEditor和vue-quill-editor的使用详解

    Vue中EpicEditor和vue-quill-editor的使用详解

    EpicEditor和Vue-quill-editor都是基于Quill.js的富文本编辑器,并且都提供了许多强大的功能,下面我们就来介绍一下二者的具体使用,感兴趣的小伙伴可以了解一下
    2023-11-11
  • Vue编译器optimize源码分析

    Vue编译器optimize源码分析

    这篇文章主要为大家介绍了Vue 编译器optimize源码分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-07-07
  • vue省市区三联动下拉选择组件的实现

    vue省市区三联动下拉选择组件的实现

    本篇文章主要介绍了vue省市区三联动下拉选择组件的相关知识。具有很好的参考价值。下面跟着小编一起来看下吧
    2017-04-04

最新评论