axios+.net core 实现上传图片

.net core ,不用[frombady],不然会识别为string类型(swagger测试)

 [ApiController]
    public class ImageController : ControllerBase
    {
        [HttpPost]
        public IActionResult UploadImage(IFormFile file)
        {

            return Ok("ok");
        }
    }

前端element

action必填,但是又涉及到跨域问题,直接用另外一个属性before-upload赋值一个方法上传

<template>
  <div class="BlogEdit">
    <el-upload
      class="upload-demo"
      ref="upload"
      action="123"
      :before-upload="upload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :auto-upload="false"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button
        style="margin-left: 10px"
        size="small"
        type="success"
        @click="submitUpload"
        >上传图片</el-button
      >
      <div slot="tip" class="el-upload__tip">
        只能上传jpg/png文件,且不超过500kb
      </div>
    </el-upload>
  </div>
</template>

JS代码,文件上传的请求应该是form格式,因此new一个formdata,this.http.uploadFile是简单封装的axios,可直接替换

data() {
    return {
      fileList: []
    };
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.fileList = fileList;
    },
    handlePreview(file) {
      console.log(file);
    },
    upload(file) {
      let fd = new FormData();
      fd.append('file', file);
      this.http.uploadFile('Image/UploadImage', fd).then((res) => {
        console.log(res);
      });
    }
  }

axios修改请求头的content-type

function uploadFile (url, param) {
  console.log(param)
  return new Promise((resolve, reject) => {
    axios.post(url, param, { headers: { 'Content-Type': 'multipart/form-data' } })
      .then(response => {
        resolve(response.data)
      })
      .catch((error) => {
        console.log(error)
        reject(error.data)
      })
  })
}

效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值