使用el-upload上传图片和post接口上传file文件;前端给后端接口上传file文件。通过formData给接口传递file文件

本文使用element-ui的el-upload图片上传功能。上传链接

在这里插入图片描述
接口参数:
在这里插入图片描述

<el-upload
  action="https://jsonplaceholder.typicode.com/posts/"
  list-type="picture-card"
  :on-success="handleAvatarSuccess"
  :on-preview="handlePictureCardPreview"
  :on-remove="handleRemove">
  <i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
  <img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
<script>
  import axios from 'axios'  // 引入
  export default {
    data() {
      return {
        dialogImageUrl: '',
        dialogVisible: false
      };
    },
    methods: {
      // 上传图片成功的接口
      handleAvatarSuccess(res, file) {
      	console.log(res)
        console.log("营业执照上传成功", file)
        console.log("营业执照上传成功:file格式---", file.raw, )
        console.log('图片地址',URL.createObjectURL(file.raw));
        const _vm = this
        this.imageUrl = URL.createObjectURL(file.raw);

		// 以下是向后端识别图片接口传递file文件
		var formData = new FormData()
        formData.append("id", _vm.$route.query.insuranceId);
        formData.append("file", file.raw); // 注意是传file.raw
        axios({
          url:'/chc-shop/api/v1/accident/thirdpartyexcessloss/businesslicense/upload',
          headers: {
            "Content-Type": "multipart/form-data",
          },
          method: "post",
          data: formData,
        })
        .then(res2 => {
          console.log('识别信息',res2);
          if (res2.data.success) {
            console.log('识别成功');
          } else {
            _vm.$message({
              message: "图片识别失败,请重新上传!",
              type: "error",
            })
          }
        })
        .catch(error => {
          console.log(error);
        })
        
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      }
    }
  }
</script>

版权声明:本文为i_am_a_div原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。