본문 바로가기

Django

Django에서의 request의 multipart 파일 처리

반응형

 

File Uploads | Django documentation | Django

File Uploads ¶ When Django handles a file upload, the file data ends up placed in request.FILES (for more on the request object see the documentation for request and response objects ). This document explains how files are stored on disk and in memory, and how to customize the default behavior. Warn...

docs.djangoproject.com

  • 오른쪽 정렬왼쪽 정렬가운데 정렬
  •  
  • 삭제

1. 올라온 파일이 Post인지 확인하고 파일 폼을 생성 한 후에 파일을 저장하면 된다.

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        handle_uploaded_file(request.FILES['fileupload'])
        return HttpResponseRedirect('write')

def handle_uploaded_file(f):
    with open('test.jpg', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)
 

2. 파일 폼 Class 정의

class UploadFileForm(forms.Form):
    title = forms.CharField(max_length=50)
    file = forms.FileField()
 

 

 

반응형

'Django' 카테고리의 다른 글

Django에 bootstrap 설치  (0) 2022.02.08
Django 서버의 static folder 파일 다운로드  (0) 2022.02.08
Django Login, Logout 템플릿 이용하기  (0) 2022.02.08
Django Auth  (0) 2022.02.08
Visual Studio Code에서 Django Debug Mode  (0) 2022.02.08