Nuxt.js File Upload

DARTZ·2022년 7월 29일
0

Vue, Nuxt.js

목록 보기
3/3

개요

FrontEnd(Nuxt)에서 BackEnd(Wagtail)로 api를 통해 사진을 전송하는 기능을 정리 해보려고 한다. 방법은 간단한데 File객체와 FormData의 이해가 부족해서 시간이 오래 걸렸었다.

구현

흐름은 input을 통해 File을 객체를 받아오고 이를 Form에 담아 BackEnd서버에 전송하는 방식이다. 코드를 살펴보자.

index.vue

        <b-upload
          v-model="file"
          ><i class="fa-solid fa-camera"></i
        ></b-upload>

Buefy의 b-upload를 사용했다. 파일을 업로드 하면 file 변수에 File객체가 담긴다.

watch {
    file: {handler(value, oldValue) {
      this.uploadFile(value);
    }}
}

watch를 통해서 file 변수의 변화를 감지하고 바뀌었을 경우 uploadFile 함수를 실행한다.

    async uploadFile(value) {
      const frm = new FormData();
      frm.append('file', value);
      await this.$store.dispatch(`fassion/postItem`, frm);
                      this.$buefy.toast.open({
                    message: '사진이 업로드 되었습니다!',
                    type: 'is-success'
                })
      this.$router.go();
    },

받아온 File객체를 file이라는 key값으로 FormData에 담는다.

    const response = await this.$axios.post(
      `/fassion/`,
      data
    )

이후 axios를 통해 서버에 전송하면 된다.

@router.post("/")
def upload(request, file: UploadedFile = File(...)):
    fassion_image = Image.objects.create(file=file, title=file._name)
    fassion = Fassion.objects.create(image=fassion_image, user=request.auth)

    return 200

API는 Django Ninja를 사용했다.
Django의 Uploaded함수를 통해 Form객체를 확인한다. Wagtail에서는 Image모델의 file에 받아온 file을 넣으면 간단하게 저장이 된다.

profile
사람들이 비용을 지불하고 사용할 만큼 가치를 주는 서비스를 만들고 싶습니다.

0개의 댓글