1. 程式人生 > 其它 >axios+.net core 實現上傳圖片

axios+.net core 實現上傳圖片

技術標籤:前後端分離筆記vue.js

.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)
      })
  })
}

效果