向Django服务器请求时,不支持的媒体类型“ multipart / form-data; boundary = ---- WebKitFormBoundaryABC”

时间:2019-12-11 22:18:41

标签: javascript python django angular typescript

我正在将一组数据(文件,字符串,数字,布尔值)上传到Django API。文档说Note: the schema is not json it's multipart,所以我使用了formData,它是多部分的。但是,当我上传此表单时,出现此错误

  

“不受支持的媒体类型” multipart / form-data;   boundary = ---- WebKitFormBoundaryABC“中的请求”

所以我尝试添加内容类型多部分httpheader,但这也导致了错误:

  

请求中不受支持的中介“ multipart”

我实际上不知道错误在哪里。要么在api中,要么在我的前端代码中,因此我将在此处添加两者的基本部分:

Django:

models.py

class Post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='posts', on_delete=models.CASCADE)

    src = models.ImageField(blank=False, null=False, editable=False, upload_to=utils.get_file_path,)
    date_posted = models.DateTimeField(auto_now_add=True, editable=False)
    last_modified = models.DateTimeField(auto_now=True)
    when = models.FloatField(blank=True, null=True)
    lock = models.BooleanField(default=False)
    des = models.CharField(
        max_length=100,
        validators=[
            RegexValidator(
                regex='^[-_a-zA-Z0-9\.]+$',
                message='only 1 to 20 characters and only letters, numbers, point, minus and underscore are allowed',
            ),
        ])

view.py

  @swagger_auto_schema(request_body=doc_serializer.CreatePostDummy, responses={201: PostSerializer})
        def create(self, request, *args, **kwargs):
            """permission required: authenticated. Note: the schema is not json it's multipart"""
            return super().create(request, *args, **kwargs)

doc_serializers.py

class CreatePostDummy(serializers.HyperlinkedModelSerializer):
    user = serializers.HyperlinkedRelatedField(required=False, read_only=True, view_name='user-detail')
    src = serializers.CharField(required=True, help_text='Not Char but image upload field')

前端

upload.ts

  ngOnInit() {

    this.categoryForm = new FormGroup({


      'lock': new FormControl(true),

      'des': new FormControl('', Validators.compose([
        Validators.maxLength(25),
        Validators.minLength(1),
        Validators.required
      ])),

      'image': new FormControl(null),
      'when': new FormControl(null),
    });

}

apiSubmit() {
  const formData = new FormData();
  formData.append('lock', this.categoryForm.get('lock').value);
  formData.append('des', this.categoryForm.get('des').value);
  formData.append('image', this.categoryForm.get('image').value);
  formData.append('when', this.categoryForm.get('when').value);


  this.http.post<any>(`{this.url}`, formData).subscribe(
    (res) => console.log(res),
    (err) => console.log(err)
  );
}

0 个答案:

没有答案