Can not send file to the .net core API from Axios (vue-nuxt)

社会主义新天地 提交于 2021-01-29 05:44:34

问题


I get back 500 errors if i try to send a file from Vue to my API endpoint in .net Core

I followed tutorials who do this, but they do not seem to work for this setup.

.net core API:

    [Route("api/[controller]")]
    [ApiController]
    public class FileUploadController : ControllerBase
    {

        [HttpPost("[Action]")]
        public string sendFiles([FromBody]FileUploadAPI file)
        {
            return "Yes!";
        }

        public class FileUploadAPI
        {
            public IFormFile File { get; set; }
        }
    }

Vue:


      this.$axios.post(
        'https://localhost:44352/api/fileupload/sendFiles',
        event.target.files[0],
        )  
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
      }); 

I want to receive my file in the API Request failed with status code 500


回答1:


You would get a 404 error because you're using the wrong URL.

Your action name is sendFiles (plural) so the correct URL path would be /api/FileUpload/sendFiles.

Axios is capable of handling FormData correctly as a multipart/form-data request. You do not need to set headers (which were incorrect anyway), nor should you wrap the data in an object.

let data = new FormData();
data.append('file', files[0]); // assuming "files" refers to a FileList

this.$axios.post('https://localhost:44352/api/FileUpload/sendFiles', data)
    .then(...)



回答2:


Following example code snippet may be help for you. In it I am using vuetify, vue-upload-component and axios to upload an image.

 <template lang="html">
  <div class="imageUploader">
    <!-- <v-card> -->
      <!-- <div v-show="$refs.upload && $refs.upload.dropActive" class="drop-active"></div> -->
      <div class="avatar-upload">
        <div class="text-center p-2">
          <div class="avatar-container">
            <div class="no-image" v-if="files.length === 0 && file == ''">
              <v-icon>cloud_upload</v-icon>
            </div>
            <template v-else>
              <img :src="file" alt="">
            </template>
          </div>
        </div>
        <div class="text-center p-2">
          <v-btn class="browse-btn" flat>
            <file-upload
              extensions="gif,jpg,jpeg,png,webp"
              accept="image/png,image/gif,image/jpeg,image/webp"
              name="avatar"
              v-model="files"
              @input="uploadImage"
              ref="upload">
              Choose File
            </file-upload>
          </v-btn>
        </div>
      </div>
    <!-- </v-card> -->
  </div>
</template>

<script>
import Cropper from 'cropperjs'
import VueUploadComponent from 'vue-upload-component'
//import axios from 'axios'

export default {
  components: {
    'file-upload': VueUploadComponent
  },
  props: ['order', 'imageURL'],
  data() {
    return {
      dialog: false,
      files: [],
      edit: false,
      cropper: false,
      file: '',
    }
  },
  mounted() {
    if (this.imageURL) {
      this.file = this.$baseURL+'document/downloadimage/' +  this.imageURL
    }
  },
  watch: {
    imageURL() {
      if (this.imageURL) {
        this.file = this.$baseURL+'document/downloadimage/' +  this.imageURL
      }
    },
  },

  methods: {
  **uploadImage(file) {
    let formData = new FormData();
    formData.append('file', file[0].file);

    axios.post(axios.defaults.baseURL + 'document/uploadimage', formData, {headers: {'Content-Type': 'multipart/form-data'}})
      .then((response) => {
        this.dialog = false
        this.$emit('upload', {id: response.data.result[0].objectId, order: this.order})
        this.file = this.$baseURL+'document/downloadimage/' + response.data.result[0].objectId

        let reader = new FileReader()
        reader.readAsDataURL(file[0].file)
        reader.onload = () => {
          let base64 = reader.result.split(',')[1]
          this.$emit('base64', base64)
          }

        this.getDimensions(this.$baseURL+'document/downloadimage/' + response.data.result[0].objectId, (result) => {
          this.$emit('dimensions', {width: result.width, height: result.height})
        })


      })
      .catch((error) => {
        console.log(error)
      })
    },**

    getDimensions(url, callback) {
      var img = new Image();
      img.src = url
      img.onload = function() {
        var result = {width: this.width, height: this.height}
        callback(result)
      }

    }
  },

}
</script>


来源:https://stackoverflow.com/questions/56248445/can-not-send-file-to-the-net-core-api-from-axios-vue-nuxt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!