我是DRF的新手,我根据官方文档构建了一个简单的api evrything效果很好,但是当我想上传img文件时 request.data为空
request.data = ----> <QueryDict: {}>
所以如果有人可以帮助
角度.serviece.ts
const httpOptions_multipart = {
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data',
'Authorization': 'Token 28----------------------8d01ab33e1df'
})
};
UploadImage(img):Observable<Image> {
console.log(img);
return this.http.put<Image>(this.profileUrl, img, httpOptions_multipart)
}
角度.component.ts
fileToUpload: File = null;
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
console.log('get item ');
var reader = new FileReader();
reader.onload = (event:any){
this.imgUrl = event.target.result;
}
reader.readAsDataURL(this.fileToUpload)
}
uploadFileToActivity(){
this.productservice.UploadImage(this.fileToUpload).subscribe(data =>{
console.log(data);
}, error => {
console.log(error);
});
}
django rest框架model.py
class Profile(models.Model):
name = models.CharField(max_length=200)
bio = models.TextField(blank=True)
pic = models.ImageField(upload_to='pics', blank=True)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
views.py
class ProfileViewSet(viewsets.ModelViewSet):
serializer_class = ProfileSerializer
queryset = Profile.objects.all()
@decorators.action(
detail=True,
methods=['PUT'],
serializer_class=ProfilePicSerializer,
parser_classes=(MultiPartParser,)
)
def pic(self, request, pk):
print ('request.data = ----> ',request.data)
obj = self.get_object()
print(obj)
serializer = self.serializer_class(obj, data=request.data,
partial=True)
if serializer.is_valid():
serializer.save()
return response.Response(serializer.data)
return response.Response(serializer.errors,
status.HTTP_400_BAD_REQUEST)
serializers.py
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ['name', 'bio', 'pic']
read_only_fields = ['pic']
class ProfilePicSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ['pic']
settings.py
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DEFAULT_PARSER_CLASSES': (
# 'rest_framework.parsers.JSONParser',
# 'rest_framework.parsers.FileUploadParser',
# 'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
}
或者是否有其他方法比 我只需要任何方式上传图片 我是编程新手,谢谢
答案 0 :(得分:0)
问题是put方法不支持angular 6中的多部分表单数据。使用post方法代替put将解决您的问题。