I am trying to record and upload an audio to django server using rest framework. My audio is getting recorded as well as the server is working fine. But they aren't working together. I am getting a status 400 Bad request. I have tried using both axios and fetch() in react but nothing is helpful.
This is when I use axios :

This is react code:
onStop(recordedBlob) {
var headers ={
'Content-Type' : 'multipart/form-data'
}
const data = new FormData();
data.append('audio', recordedBlob);
console.warn(recordedBlob);
/* fetch("http://127.0.0.1:8000/temp/",{
method:'POST',
body:data,
headers:headers
}).then( res => console.log(res)).catch(error => {
console.log(error);
})*/
axios.post("http://127.0.0.1:8000/temp/", data, { 'headers':headers
})
.then(res => {
console.warn(res);
}).catch((error)=>{
console.log(error);
});
}
My django views file :
class AudioCreateView(ModelViewSet):
queryset=Audio.objects.all()
serializer_class = AudioSerializer
def create(self, request, *args, **kwargs):
if 'file' not in request.data:
raise ParseError('No File Uploaded')
file_obj = request.data['audio']
# do some stuff with uploaded file
Audio.objects.create(audio=file_obj)
return Response(data="File Received")
My serializers file :
class AudioSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model= Audio
fields = ['audio']
My django settings :
INSTALLED_APPS = [
'corsheaders',
'lang_translator.apps.LangTranslatorConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework'
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL= "/media/"
REST_FRAMEWORK={
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]
}
CORS_ORIGIN_ALLOW_ALL=True
My django Model :
from django.db import models
class Audio(models.Model):
audio = models.FileField(upload_to='images/')
I finally found out the problem. The problem is with the audio blob recorded. When I tried to upload audio and image files using new html file and postman. The server worked perfectly fine in both of those situations. I just need to find another way to record and send audio with react. Does anyone have any idea for this ?
