Search code examples
djangodjango-rest-frameworkdjango-file-upload

uploading image to django rest model


I am trying to upload image to Images folder which under the media directory. I am using following APIView on my views.py;

class FileUploadView(APIView):
    parser_classes = (FileUploadParser,)

    def post(self, request, format='jpg'):
        up_file = request.FILES['file']
        destination = open('C:\\Users\\cano\\Desktop\\workspace\\campusBackend\\campusBackend\\media\\Images', 'wb+')
        for chunk in up_file.chunks():
            destination.write(chunk)
            destination.close()
            return Response(up_file.name, status.HTTP_201_CREATED)

However, when I sent request, it gives me the following error;

> PermissionError: [Errno 13] Permission denied:
> 'C:\\Users\\cano\\Desktop\\workspace\\campusBackend\\campusBackend\\media\\Images'
> [12/Dec/2016 15:10:45] "POST /imageUpload HTTP/1.1" 500 19170

I have already added MEDIA_ROOT and MEDIA_URL in settings.py;

> MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
> 
> MEDIA_URL = '/media/'

Solution

  • Try this:

    destination = open('C:\\Users\\cano\\Desktop\\workspace\\campusBackend\\campusBackend\\media\\Images' + up_file.name, 'wb+')
    

    With your code you are trying to rewrite a directory not a file.