Django로 instagram 만들어보기 (4) - 파일 업로드

swb·2022년 11월 27일
0

django

목록 보기
5/11

0. 비동기 처리

  • 비동기 : 사람이 무슨 요청을 했는데 오래 걸려. 그럴 때
    딴 짓 할 수 있는 것

1. 파일 업로드

  • 작성한 글, 이미지, 사용자 ID, 사용자 Profile을 서버에 올려야 한다.
  • ajax로 장고 views.py에 UploadFeed() class로 보냈다.
    main.html
       $.ajax({
           url: "/content/upload",
           data: fd,
           method: "POST",
           processData: false,
           contentType: false,
           success: function(data){
               console.log("성공");
           },
           error: function(request, status, error){
               console.log("실패");
           },
           complete: function(){
               console.log("완료");
               location.replace("/");
           }
       })

content/views.py

class UploadFeed(APIView):
    def post(self, request):
        # 일단 파일 불러오기
        file = request.FILES['file']
        # 특수문자, 한글 등이 오면 오류가 나서 랜덤으로 id값(영어+숫자)
        uuid_name = uuid4().hex
        save_path = os.path.join(MEDIA_ROOT, uuid_name)
        # 파일 저장
        with open(save_path, 'wb+') as destination:
            for chunk in file.chunks():
                destination.write(chunk)

        content = request.data.get('content')
        image = uuid_name
        profile_image = request.data.get('profile_image')
        user_id = request.data.get('user_id')

        # 피드에 나타내기
        Feed.objects.create(content=content, image=image, profile_image=profile_image, user_id=user_id, like_count=0)

        return Response(status=200)
  • 이미지 이름 변경을 위해 uuid 사용
  • 이미지 저장을 위해 save
  • 이미지들은 media 폴더에 저장된다.

3. media에 있는 파일을 화면에 보여주기

  • head부분에
{% load static %}
  • body부분에
{% get_media_prefix %}{{ feed.image }}

출처

profile
개발 시작

0개의 댓글