若依前后端分離 Vue el-upload單圖片上傳


參考於:原文鏈接:https://blog.csdn.net/qq_42751248/article/details/107326737

一、前端相關:

<!--: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} 個!`); }, } };

注:在提交事件中添加: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";
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM