Загрузка файлов в s3 bucket для приложения на react js и django

Я пытаюсь использовать службы ASW s3 для загрузки файлов. При нажатии на кнопку для загрузки файла пользователь должен иметь возможность выбрать файл со своего компьютера и загрузить его в ведро s3.

Следующий код был выполнен мной

views.py

def upload_file(file_name, object_name=None):
    """Upload a file to an S3 bucket

    :param file_name: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """

    # If S3 object_name was not specified, use file_name
    if object_name is None:
        object_name = os.path.basename(file_name)

    # Upload the file
    s3_client = boto3.client('s3')
    try:
        response = s3_client.upload_file(file_name, 'my-bucket', object_name)
    except ClientError as e:
        logging.error(e)
        return False
    return True

urls.py - приложение для Django

router = DefaultRouter()
router.register(r'userdata', UserDataViewSet)
router.register(r'education', EducationViewSet)
router.register(r'workexperience', WorkExperienceViewSet)
router.register(r'clientregistration', ClientRegistrationViewSet)
router.register(r'jobdescription', JobDescriptionViewSet)
router.register(r'assessment', AssessmentViewSet)
router.register(r'appointment', AppointmentViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('api/recruiters/', get_recruiters, name='get_recruiters'),
    path('api/clients/', get_clients, name='get_clients'),
    path('submit-assessment/', submit_assessment, name='submit_assessment'),
    path('api/amanager/', get_accoutmanagers, name='get_accountmanagers'),
    path('api/job-descriptions/', get_job_descriptions, name='get_job_descriptions'),
    path('api/job-descriptions/<int:job_id>/assessments/', get_assessments_for_job, name='get_assessments_for_job'),
    path('clientregistration/', ClientRegistrationViewSet.as_view({'post': 'create'}), name='clientregistration'),
    path('api/get_user_details/', get_user_details, name='get_user_details'),
    path('submit_user_data/', submit_user_data, name='submit_user_data'),
    path('upload_file/', upload_file, name='upload_file')
]

А на моем react frontend

const handleUploadResume = () => {
        // Assuming 'resumeFile' is the name of your file input field
        const fileInput = document.querySelector('input[type="file"]');
        const formData = new FormData();
        formData.append('resume', fileInput.files[0]);
    
        axios.post('/upload_file/', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        .then(response => {
            console.log('File uploaded successfully:', response.data);
            // Reset the form after successful submission
            fileInput.value = ''; // Clear the file input field
        })
        .catch(error => {
            console.error('Error uploading file:', error);
        });
    };

При нажатии на кнопку на странице я получаю следующую ошибку

Error

Любая помощь будет оценена по достоинству, спасибо!

Вернуться на верх