Django Rest Framework:无法序列化或保存上传的图像

时间:2018-02-04 19:28:35

标签: django django-rest-framework django-settings django-serializer django-uploads

无法在APIview中序列化或保存上传的图像。 如果保存,文件将被破坏且无法打开。如果序列化,得到: {“avatar”:[“没有提交文件。”]} 请求内容:

MultiValueDict: {u'name': [<TemporaryUploadedFile: Avatar.jpg (image/jpeg)>]}

设定:

FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.TemporaryFileUploadHandler',
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')

网址:

urlpatterns = [
url(r'^test/$', TestReturn.as_view(), name='test-detail'),
url(r'^users/$', UserProfileAll.as_view(), name='userprofile-detail'),
url(r'^avatar/', UploadAvatar.as_view(), name='images')

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

型号:

class AvatarStorage(models.Model):
avatar = models.ImageField(verbose_name="Uploaded image", upload_to='media', null=True)

Serialzier:

class AvatarStorageSerializer(serializers.ModelSerializer):
avatar = serializers.ImageField(use_url=True)

class Meta:
    model = AvatarStorage

    fields = '__all__'

查看:

class UploadAvatar(APIView):
parser_classes = (MultiPartParser,)

def post(self, request, format=None):

    serializer = AvatarStorageSerializer(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)

对于发布,我使用Postman,在那里设置:Body =&gt; Form-Data并从磁盘中选择一个文件。

如果重要,那就是移动API

2 个答案:

答案 0 :(得分:1)

将设置文件FILE_UPLOAD_HANDLERS更新为此

$combo = explode('.',$this->storeNamesCombo);

$storeClasses = ArrayHelper::map(StoreClasses::find()->all(), 'id', 'name');
$storeFamilies = ArrayHelper::map(StoreFamilies::find()->all(), 'id', 'name');
$storePlatforms = ArrayHelper::map(StorePlatforms::find()->all(), 'id', 'name');

$mc_search = [];
$mf_search = [];
$mp_search = [];

foreach($combo as $item){
    $temp_mc = array_search($item, $storeClasses);
    if($temp_mc !== False){ $mc_search[] = $temp_mc; }

    $temp_mf = array_search($item, $storeFamilies);
    if($temp_mf !== False){ $mf_search[] = $temp_mf; }

    $temp_mp = array_search($item, $storePlatforms);
    if($temp_mp !== False){ $mp_search[] = $temp_mf; }
}


if(!empty($mc_search)){
    foreach($mc_search as $item){
        $query->andFilterWhere(['or', '"storeNames"."classId"' => $item]);    
    }

}
if(!empty($mf_search)){
    foreach($mf_search as $item){
        $query->andFilterWhere(['or', '"storeNames"."familyId"' => $item]);    
    }
}
if(!empty($mp_search)){
    foreach($mp_search as $item){
        $query->andFilterWhere(['or', '"storeNames"."platformId"' => $item]);
    }
}

if(!empty($combo)){
    foreach($combo as $item){
        $query->where(['ilike', '"storeNames"."subFamilyName"', $item],
            ['ilike', '"storeNames"."variantName"', $item]);
    }
}

如果您想了解更多信息,read this

答案 1 :(得分:0)

问题不在代码中,我在Postman中缺少必需的标题:

Content-Disposition: attachment; filename=upload.jpg;