当前位置:   article > 正文

elementui 图片上传,手动实现图片上传,入库并实现预览效果(轮播展示)_elementui上传图片预览

elementui上传图片预览

需求:
点击操作按钮,选择上传,弹出上传dialog,使用upload组件实现图片上传,并可在前端进行预览
在这里插入图片描述
先看上传
前端实现:

弹出框

    <el-dialog

      :title="titleFlag"
      :visible.sync="uploadFlag"
      width="30%"
      :close-on-click-modal="false"
      class="uploadFlag"
      @close="()=>{this.fileListDate=[];this.uploadFlag = false}"
    >
      <div
        v-loading="loading"
        element-loading-text="拼命上传中"
        element-loading-spinner="el-icon-loading"
      >
        <span>温馨提示:该类型为重要材料,上传重要材料可降低用工风险</span>
        <div style="margin-top: 20px;">
          <el-form>
            <el-form-item>
              <el-upload
                ref="upload"
                class="upload-demo"
                drag
                :http-request="uploadAvatar"
                :on-remove="handleRemove"
                :file-list="fileListDate"
                :before-upload="beforeAvatarUpload"
                action="#"
                :limit="1"
                :on-exceed="handleExceed"
                accept=".jpg,.jpeg,.png,.doc,.docx,.pdf,.excel,.xlsx,.xls"
                :on-progress="fileProgress"
              >
                <i class="el-icon-upload" />
                <div>
                  <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
                  <div slot="tip" class="el-upload__tip">文件不超过10M</div>
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
          <!--<div slot="footer" class="dialog-footer">
            <el-button @click="uploadFlag = false">取 消</el-button>
            <el-button type="primary" @click="onSubmit()">确 定</el-button>
          </div>-->
          <div slot="footer" class="dialog-footer" style="text-align: right;">
            <el-button @click="()=>{this.fileListDate=[];this.uploadFlag = false}">取 消</el-button>
            <el-button type="primary" @click="onSubmit">确 定</el-button>
          </div>
        </div>
      </div>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

data中主要参数:

data(){
 return{
 // 存储时使用
 	photolData: {
        userId: this.$route.params.userId,
        materialType: '',
        filePath: '',
        dataType: '1'
      },
      // 图片列表
     fileListDate: [],
     // 预览时使用
      imgList: [],
      }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

methods:

// 方法名
 uploadAvatar(data) {
      const formData = new FormData()
      formData.append('avatarfile', data.file)
      formData.append('userId', this.photolData.userId)
      formData.append('materialType', this.photolData.materialType)
      this.loading = true
      // 后台接口
      uploadAvatar(formData).then(response => {
        this.fileListDate.push({ name: data.file.name, url: response.msg })
        this.loading = false
      })
    },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

js中定义后台接口:

// 上传材料附件
export function uploadAvatar(data) {
  return request({
    url: '/aa/bbb/avatar',
    method: 'post',
    data: data
  })
}
// 保存上传图片
export function addPhoto(data) {
  return request({
    url: '/aaa/bbb/addPhotoInfo',
    method: 'post',
    data: data
  })
}
// 预览个人证件照
export function previewPhoto(userId, materialType) {
  return request({
    url: '/aaa/bbb/previewPhotoByUserId?userId=' + userId + '&materialType=' + materialType,
    method: 'get',
  })
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

当前页面引用js中的方法

import {uploadAvatar,addPhoto,previewPhoto} from '@/api/aaa/bbb/xxx.js'
  • 1

浏览器中的请求:
在这里插入图片描述
在这里插入图片描述
后台实现:

  /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file, String userId, String materialType) throws IOException {
        if (!file.isEmpty()) {
            String name = file.getOriginalFilename();
            String avatar = "";
            if (name.endsWith("jpg") || name.endsWith("jpeg") || name.endsWith("png")) {
                avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
            } else {
                avatar = FileUploadUtils.upload(RuoYiConfig.getDownloadPath(), file);
            }

            String remark = "";
            if (avatar != null) {
                for (int x = 0; x < fileType.length; x++) {
                    if (materialType.equals(fileType[x])) {
                        remark = "上传了" + materialType;
                        operatorRecordService.insertOperarot(userId, remark);
                        return AjaxResult.success(avatar);
                    }
                }
                remark = "上传了" + materialType + "失败";
                operatorRecordService.insertOperarot(userId, remark);
                return AjaxResult.success(avatar);
            }
            return AjaxResult.success(avatar);
        }
        return AjaxResult.error("上传图片异常,请联系管理员");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

工具类: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);
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

获取图片路径,使用如若依框架自带的:RuoYiConfig

  /**
     * 获取头像上传路径
     */
    public static String getAvatarPath()
    {
        return getProfile() + "/avatar";
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

上传成功后返回路径:
在这里插入图片描述
前端展示:
在这里插入图片描述
接下来就是将路径保存到数据库,然后前端页面点击预览,查看上传的图片:
methods中的submit方法:

  onSubmit() {
      this.photolData.filePath = JSON.stringify(this.fileListDate)
      if (this.photolData.filePath === '[]') {
        return this.msgError('上传文件不能为空!')
      }
      // 调用接口
      addPhoto(this.photolData).then(resp => {
        if (resp.code === 200) {
          this.msgSuccess('提交成功')
          this.getInitData()
          this.uploadFlag = false
        }
      })
    },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

浏览器中的请求格式:
在这里插入图片描述
在这里插入图片描述
后台:

// 材料常量(随意写的)
public static final String[] fileType = {"照片", "照片2","照片3","照片4","照片5","照片6","照片7","照片8"};
  • 1
  • 2
  @PostMapping("/addPhotoInfo")
    public AjaxResult addPhotoInfo(@Validated @RequestBody Photo photo) {
        photo.setCreateBy(getUsername());
        List<UploadVo> uploadVo = JSONArray.parseArray(photo.getFilePath()).toJavaList(UploadVo.class);
        String urlName = "";
        if (StringUtils.isNotNull(uploadVo) && uploadVo.size() > 0) {
            urlName = uploadVo.get(0).getName();
        }

        //
        if (urlName.endsWith("jpg") || urlName.endsWith("jpeg") || urlName.endsWith("png")) {
            photo.setIsPic("0");
        } else {
            photo.setIsPic("1");
        }
        int i = photoService.insertPhotoInfo(photo);
        String remark = "";
        if (i > 0) {
            for (int x = 0; x < fileType.length; x++) {
                if (photo.getMaterialType().equals(fileType[x])) {
                    remark = "新增" + photo.getMaterialType();
                    operatorRecordService.insertOperarot(photo.getUserId(), remark);
                    return toAjax(i);
                }
            }
            remark = "新增" + photo.getMaterialType();
            operatorRecordService.insertOperarot(photo.getUserId(), remark);
            return toAjax(i);
        }
        return toAjax(i);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

UploadVo :主要用于将filePath中的信息存储起来

public class UploadVo {
    private Long uid;

    private String name;

    private String url;

    private String success;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

在这里插入图片描述
然后调用新增方法insertPhotoInfo入库:
在这里插入图片描述
在这里插入图片描述
入库成功
在这里插入图片描述
然后点击预览,进行查看
在这里插入图片描述
预览(轮播展示):
前端效果:
在这里插入图片描述
前端实现:
预览dialog

 <!--证件预览-->
    <el-dialog :title="previewTitle" :visible.sync="previewFlag" width="40%" :close-on-click-modal="false">
      <el-carousel
        indicator-position="none"
        arrow="always"
        :autoplay="false"
        @change="((pre, next) => {imgChange(pre, next)})"
      >
        <el-carousel-item v-for="(item,index) in imgList" :key="index">
          <div v-if="item.type==='0'" style="text-align: center;">
            <img :src="item.url" style="height: 300px">
          </div>
          <div v-if="item.type==='1'" style="display: flex; justify-content: space-around; align-items: center; padding: 0 10%; height:100%;">
            <el-image :src="require('@/assets/images/excel.png')" style="width: 220px;" />
            <el-button type="primary" plain style="height:36px;" @click="down(item.url)">下载文档</el-button>
          </div>

        </el-carousel-item>
      </el-carousel>
    </el-dialog>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
// 预览方法
    previewFile(fileType) {
      this.previewFlag = false
      this.imgList = []
      previewPhoto(this.photoData.userId, fileType).then(resp => {
        if (resp.code === 200) {
          if (resp.data) {
            this.previewFlag = true
            for (let i = 0; i < resp.data.length; i++) {
              this.imgList.push({ type: resp.data[i].isPic, url: process.env.VUE_APP_BASE_API + JSON.parse(resp.data[i].filePath)[0].url })
            }
          } else {
            this.$message.warning('暂无数据,请先上传')
          }
        }
      })
    },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

浏览器中的请求格式:
在这里插入图片描述
在这里插入图片描述

后台:就是根据userId和证件类型去查询

  /**
     * 预览个人证件照
     *
     * @param userId
     * @return
     */
    @GetMapping("/previewPhotoByUserId")
    public AjaxResult previewPhotoByUserId(String userId, String materialType) {
        List<Photo> photo= photoService.previewPhotoByUserId(userId, materialType);
        String remark = "";
        if (photo!= null) {
            for (int x = 0; x < fileType.length; x++) {
                if (materialType.equals(fileType[x])) {
                    remark = "预览了" + materialType;
                    operatorRecordService.insertOperarot(photo.get(0).getUserId(), remark);
                    return AjaxResult.success(photo);
                }
            }
        }
        return AjaxResult.success(photo);
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

xml中:

 <select id="previewPhotoByUserId" parameterType="String" resultMap="BaseMaterialResult">
        select id, user_id, material_type, file_path, is_pic
        from photo
        where user_id = #{userId}
          and material_type = #{materialType}
          and file_path !='[]'
    </select>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

接口返回的数据,主要看filePath
在这里插入图片描述

预览时需要给url添加前缀
在这里插入图片描述
最终展示(轮播展示的):
在这里插入图片描述
在这里插入图片描述
至此就完成了~,记录一下,仅供参考。
描述有误的地方欢迎大家指正,大家有问题可加qq 876942434。一起进步~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/251001
推荐阅读
  

闽ICP备14008679号