Skip to content
Advertisement

How can i get formdata with .net core web api and vue.js

I am trying to write an announcement system. i am using vue 2 and net core 3.1. The announcement has a photo, title, and content. (The department id field is static for now.) I’m trying to send the announcement’s information with the photo in the formdata, but the api can only capture the photo. So where am I going wrong? This is my vue component:

 <template>
  <div class="d-flex justify-content-center pt-5">
    <Sidebar/>
    <form @submit.prevent="onSubmit" enctype="multipart/form-data">
      <div class="mt-5">
      <h1 style=" text-align: center;">Text Editor</h1>
      <client-only>
      <VueEditor v-model="post.content" />
      </client-only>
      <div class="form-group">
        <label for="">Başlık</label>
        <input v-model="post.title" type="text" class="mt-5">
      </div>
      <div class="form-group">
        <label for="">Department</label>
        <input v-model="post.departmentId" type="text" class="mt-5">
      </div>
      <div class="form-group">
        <label for="">Foto</label>
        <input  type="file" @change="uploadFile" ref="file" class="mt-5">
      </div>
      <button type="submit" class="btn btn-info mt-5">Kaydet</button>
      </div>
    </form>
  </div>
</template>

<script>
import Sidebar from '../components/sidebar/Sidebar.vue'
import { VueEditor } from "vue2-editor";
export default {
  components: {
    Sidebar,
    VueEditor
  },

  data(){
    return {
      post : {
        title : "",
        content : "",
        departmentId : 1,
      },
      imagePath : ""
    }
  },

  methods : {
    uploadFile(event) {
        this.imagePath = event.target.files[0];
      },
    onSubmit(){
      const formData = new FormData();
      // let data = new Blob([JSON.stringify(this.post)], {
      //   type: 'application/json'
      // })
      formData.append('ImagePath', this.imagePath, 'ImagePath');
      
      //formData.append('Title', this.post.title); //this is for try
      
      let endPoint = 'Notice/add';
      // console.log({formData,...this.post})
      this.$axios.post(this.$apiUrl + endPoint , formData,
                {headers: {
                    "Content-Type": "multipart/form-data",
                    "Authorization" : "Bearer "+ this.$store.getters.getToken
                }})
        .then(response => {
          console.log(response)
        })
        .catch(e => console.log(e))
    }
  }
}
</script>

and this is my api controller:

[HttpPost("add")]
        public IActionResult Add([FromForm(Name = "ImagePath")] IFormFile formFile, [FromForm(Name = "Title")]Notice notice)
        {

            notice.file = formFile;
            var result = _noticeService.Add(notice);
            if (result.Success)
            {
                return Ok(result);
            }
            else
            {
                return BadRequest(result);
            }
        }

and this is Notice Entity:

public class Notice: IEntity
    {
        [Key]
        public int Id { get; set; }
        public int DepartmentId { get; set; }
        public string Title { get; set; }

        public string Content { get; set; }
        public DateTime Created_At { get; set; }
        public DateTime Updated_At { get; set; }
        public string ImagePath { get; set; }
           
        [NotMapped]
        public  dynamic file { get; set; }
    

    }

if i miss anything  you can tell me and i will update this entry immediately. thanks.

Advertisement

Answer

for this blog:Upload file using vue js ASP.NET Core

you can use the follow code:

public string Upload_File()

    {

        string result = string.Empty;

        try

        {

            long size = 0;

            var file = Request.Form.Files;

            var filename = ContentDispositionHeaderValue.Parse(file[0].ContentDisposition).FileName.Trim('"');

            string FilePath = hostingEnv.WebRootPath +Path.DirectorySeparatorChar.ToString()+ $"{filename}";

            size += file[0].Length;

            using (FileStream fs = System.IO.File.Create(FilePath))

            {

                file[0].CopyTo(fs);

                fs.Flush();

            }

            result = FilePath;

        }

        catch (Exception ex)

        {

            result = ex.Message;

        }

        return result; 

    }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement