조회수 : 5675
django file upload (multifile upload too)장고에서 파일 업로드
model 을 통한 model form 은 많은 예제가 있고,
forms 에 form 을 이용한 것이다.

  1. forms.py 설정
  2. views.py 
  3. index.html



  1. forms.py
from django import forms

class UploadFileForm(forms.Form):
    name = forms.CharField(max_length = 15)
    # files = forms.FileField()
    files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))


  1. views.py

from django.shortcuts import render, redirect
import os
from .forms import UploadFileForm
from django.http import HttpResponse

# Create your views here.
def index(request):
    form = UploadFileForm()
    if request.method == 'POST':
        print(os.getcwd())
        print("POST method")
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            print("Valid")
            for count, x in enumerate(request.FILES.getlist("files")):
                def handle_uploaded_file(f):
                    with open(os.path.join(os.getcwd(),"media", f.name),'wb+') as destination:
                        for chunk in f.chunks():
                            destination.write(chunk)
                handle_uploaded_file(x)
                print(x.name)
                os.remove("media/"+str(x.name))
                print(str(x.name)+"삭제완료")
            context = {'form':form,}
            return render(request, 'fileupload/index.html', context)
            # return HttpResponse(" File uploaded! ")
    else:
        form = UploadFileForm()

    return render(request, 'fileupload/index.html', {'form': form})

# 이런 식으로도 가능하다
# ssw makes this for single file upload

# def upload(request):
#     flist = request.FILES.getlist('files')
#     for f in flist:
#         tmp = open(os.path.join(os.getcwd(), 'media', f.name), 'wb+')
#         for chunk in f.chunks():
#             tmp.write(chunk)
#     return HttpResponse( " File uploaded! ")

  1. index.html

<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
  {{form}}

  <button name="choice" value="{{form.value}}">파일 올리기</button>
</form>

참고 youtube 영상

 file upload에 관한 django documents

상담을 원하시면 상담신청을 눌러 주세요

다른 포스팅 Tag Cloud