본문 바로가기
웹 개발 이야기/django

[django] input[type=file] 을 이용하여 첨부한 파일 저장

by Gommin 2023. 5. 11.

views.py

import os

def programdetailupdate(request: HttpRequest, pk: int) -> HttpResponse:
    std = Program()
    srd = Program.objects.get(id=pk)
    std.pk = pk

    if request.FILES['pimg']:
        uploaded_file = request.FILES['pimg']
        file_name = uploaded_file.name

        # 현재 날짜 가져오기
        curdt = datetime.now()
        curdty = curdt.year
        curdtm = curdt.month
        curdtd = curdt.day
        mloc = f'laboratory/program/{curdty}/{curdtm}/{curdtd}'

        folder_path = os.path.join(settings.MEDIA_ROOT, mloc)
        if not os.path.exists(folder_path):
            # 폴더가 없다면 폴더 생성
            os.makedirs(folder_path)

        file_path = os.path.join(settings.MEDIA_ROOT, mloc, file_name)
        with open(file_path, 'wb') as destination:
            for chunk in uploaded_file.chunks():
                destination.write(chunk)

        std.pimg = f'{mloc}/{file_name}'

        if srd.pimg:
                    # 기존 파일이 있을 경우
          file_path = os.path.join(settings.MEDIA_ROOT, str(srd.pimg))
          if os.path.exists(file_path):
              os.remove(file_path)
    else:
        std.pimg = srd.pimg

댓글