0

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

  • Also, I'm not sure what the `.$post()` method is. Can't see that in any of the Axios documentation. Typically, you would use `.post()` (no dollar sign) – Phil May 22 '19 at 02:40
  • After the changes, i get : Request failed with status code 415 So the inferred type is not good somehow – Johan Van Wambeke May 22 '19 at 03:02

2 Answers2

2

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(...)
Phil
  • 157,677
  • 23
  • 242
  • 245
0

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>
aamir sajjad
  • 3,019
  • 1
  • 27
  • 26