起因:

前端在上传图片的时候,希望能显示下预览。

过程:

经过在网上各种搜索,加上自己的总结,终于解决。

结果

主要逻辑是:通过文件阅读器把上传的图片文件转成二进制形式放到url里

形成如下的代码:

<template>
  <div class="main_item">
    <div class="itemLeft">
      <span class="must">商品缩略图</span>
    </div>
    <div class="itemRight">
      <!-- itemRight2 -->
      <el-upload
        action="http://localhost:8080"
        v-model="imageUrl.file"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :on-error="uploadError"
        :before-upload="beforeAvatarUpload"
        accept="image/png, image/jpg, image/jpeg"
        class="avatar-uploader"
      >
        <img v-if="imageUrl.url" :src="imageUrl.url" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: {
        url: null,
        file: null,
      },
    };
  },
  methods: {
    // 图片上传成功提示
    handleAvatarSuccess(res, file, fileList) {
      this.$message({
        center: true,
        message: "图片上传成功",
        type: "success",
      });
    },
    
    uploadError() {
      // ?不需要,上传失败操作
    },
    //上传前回调
    beforeAvatarUpload(file) {
      // ++
      console.log(file);
      this.imageUrl.file = file;
      this.imagePreview(this.imageUrl.file, 1);
      return false;
    },
    //**重点**,上传的文件转化为base64格式,用于展示
    imagePreview(file, v) {
      var self = this;
      //定义一个文件阅读器
      var reader = new FileReader();
      //文件装载后将其显示在图片预览里
      reader.onload = function (e) {
        //将bade64位图片保存至数组里供上面图片显示
        if (v == 1) {
          self.imageUrl.url = e.target.result;
        } 
      };
      reader.readAsDataURL(file);
    },
  },
};
</script>


<style scoped>
.main_item {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background: #f3f3f3;
  box-sizing: border-box;
}
.itemLeft {
  line-height: 1;
  font-size: 60px;
  font-weight: bolder;
  color: #3a17d6;
  height: auto;
  width: 50%;
  margin-bottom: 30px;
}
.itemRight {
  height: auto;
  width: 50%;
}
.avatar {
  height: auto;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-content: center;
  justify-content: center;
}
.avatar-uploader-icon {
    font-size: 30px;
}

</style>

优化

现在大多是前后端分离的,在调试时,需要设置代理。但是el-upload组件是直接上传的,这里要重写http-request属性。

思路是:

1. 先写一个上传文件的公共服务;

2. 在当前页定义一个函数:组装formData数据,然后传递给那个公共服务;

代码如下:

公共服务:这里的request是经过axios重写过的,想知道怎么重写请百度。

export function upload_image(query){
    return request({
        url: '/boss/admin/upload/image',
        method: 'post',
        data: query,
        headers: {'Content-Type': 'multipart/form-data'}
    })
}

 上传文件函数:组装formData数据并上传

import { upload_image } from "../../api/index";

upLoadImage(param){
      let formData = new FormData();
      formData.append("file", param.file);
      formData.append("files", param.files);
      upload_image(formData).then(res=>{
        this.form.file = res.data.file
      })
}

组件参数:覆盖http-request属性

<el-upload 
<el-upload 
:action="uploadActionUrl" 
:before-upload="beforeAvatarUpload"
:show-file-list="true" 
:file-list="[form.file]"
:http-request="upLoadImage"
accept="image/png, image/jpg, image/jpeg"
list-type="picture"
>
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">请上传图片格式文件</div>
</el-upload>

如有问题,请留言!