'I can't send file to django server through angular and error says: The submitted data was not a file. Check the encoding type on the form
my code is like this and I send data through httpClient and it returns error on upload my angular version is 13 and django version is 4 and I'm using django rest framework for restApi ng component
const data={
"image_url":this.imgFile,
"caption": this.caption,
'author':1
};
console.log(data);
this.service.createPost(data).subscribe(res=>console.warn(res));
}
onFileChanged(event:any) {
const reader = new FileReader();
this.file = event.target.files[0];
if(!this. file) return
reader.readAsDataURL(this.file);
reader.onload = () => {
this.imgFile = reader.result as string;
};
}
django model
caption = models.CharField(max_length=4000)
likes = models.IntegerField(default=0, blank=True)
is_liked = models.BooleanField(default=False, blank=True)
date = models.DateTimeField(auto_now_add=True)
image_url = models.ImageField(upload_to='images', blank=True)
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
def __unicode__(self):
return (self.caption)
def __str__(self):
return self.caption + ' | ' + str(self.likes)
django view
def get(self, req):
data = Post.objects.all()
serialized = PostSerializer(data, many=True)
return Response(serialized.data)
def post(self, request):
serializer = PostSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
django Serializer
class PostSerializer(serializers.ModelSerializer):
# image_url = ThumbnailerSerializer(alias='avatar')
class Meta:
model = Post
fields = '__all__'
def create(self, validated_data):
return Post.objects.create(**validated_data)
Solution 1:[1]
In your component.ts file
onFileChanged(event:any) {
const reader = new FileReader();
this.file = event.target.files[0];
this.form.patchValue({
image: this.file
})
if(!this. file) return
reader.readAsDataURL(this.file);
reader.onload = () => {
this.imgFile = reader.result as string;
};
onSubmit(){
this.service.addRecord(
this.signUpForm.value.likes,
...
this.signUpForm.value.image,
)
}
in your service.ts file
addRecord(
email: string,
...
image: File): Observable<any>{
let formData: any = new FormData();
formData.append("email", email)
...
formData.append("image", image)
return this.http.post<any>(this.APIUrl + "/post/",formData)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kennedy Eziechina |
