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.js删除列表中的一行

    vue.js删除列表中的一行

    这篇文章给大家分享了vue.js删除列表中的一行的实例操作以及代码分享,有兴趣的朋友参考下。
    2018-06-06
  • vue在.js文件中引入store和router问题

    vue在.js文件中引入store和router问题

    这篇文章主要介绍了vue在.js文件中引入store和router问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • Vuex数据的存储与获取方式

    Vuex数据的存储与获取方式

    这篇文章主要介绍了Vuex数据的存储与获取方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • vue中的el-tree @node-click传自定义参数

    vue中的el-tree @node-click传自定义参数

    这篇文章主要介绍了vue中的el-tree @node-click传自定义参数方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-08-08
  • vue开发简单上传图片功能

    vue开发简单上传图片功能

    这篇文章主要为大家详细介绍了vue开发简单上传图片功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-06-06
  • vue前端测试开发watch监听data的数据变化

    vue前端测试开发watch监听data的数据变化

    这篇文章主要为大家介绍了vue测试开发watch监听data的数据变化,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • VUE脚手架具体使用方法

    VUE脚手架具体使用方法

    这篇文章主要介绍了VUE脚手架具体使用方法,vue-cli这个构建工具大大降低了webpack的使用难度,小编觉得不错,下面就一起来了解一下具体使用方法
    2019-05-05
  • Vue3中实现div拖拽功能

    Vue3中实现div拖拽功能

    这篇文章主要介绍了Vue3中实现div拖拽功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2024-03-03
  • vue + webpack如何绕过QQ音乐接口对host的验证详解

    vue + webpack如何绕过QQ音乐接口对host的验证详解

    这篇文章主要给大家介绍了关于利用vue + webpack如何绕过QQ音乐接口对host的验证的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧
    2018-07-07
  • vue-next/runtime-core 源码阅读指南详解

    vue-next/runtime-core 源码阅读指南详解

    这篇文章主要介绍了vue-next/runtime-core 源码阅读指南详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10

最新评论