You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular向Django Rest Framework上传图片报错,求解决方案

Angular上传图片到DRF API失败的解决办法

问题详情

用Django Rest Framework搭建的API,模型包含ImageField字段,Postman以form-data格式上传图片完全正常,但Angular前端上传时触发错误:

Image: Array ['Image is not a file: check the method of codification of the formulary']

当前Angular的上传方法代码:

add(endpoint:string, data:any) {
  let url = `${this.baseUrl}/${endpoint}/`
  let datos = JSON.stringify(data)
  let token = new HttpHeaders().set('Content-Type', 'application/json').set('Authorization', `Token ${localStorage.getItem('token')}`)
  let options = {headers:token}
  return this.http.post(url, datos, options).pipe(catchError(this.handleError<any>()))
}

调试发现JSON.stringify()处理后图片字段为空,尝试改用FormData又出现JSON解析错误。

附Django相关代码:

Model代码

class Pelicula(models.Model):
    titulo = models.CharField(max_length=100)
    descripcion = models.TextField()
    imagen = models.ImageField(upload_to='peliculas', null=True, blank=True)
    reparto = models.TextField()
    director = models.CharField(max_length=100)
    duracion = models.IntegerField()
    genero = models.CharField(max_length=100)

Serializer代码

class PeliculaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Pelicula
        fields = ('titulo', 'imagen', 'descripcion', 'reparto', 'genero', 'duracion', 'director')

问题原因

  1. JSON.stringify()无法序列化File对象,直接转换会导致图片数据丢失,后端自然识别不到文件。
  2. 用FormData时出现JSON解析错误,是因为手动设置了Content-Type: application/json——FormData需要浏览器自动生成带boundary的multipart/form-data请求头,手动设置会破坏请求结构,导致DRF无法正确解析请求体。

修正方案

调整Angular上传方法

改用FormData传递数据,且不手动设置Content-Type:

add(endpoint: string, data: any) {
  const url = `${this.baseUrl}/${endpoint}/`;
  const formData = new FormData();
  
  // 将所有表单数据(包括文件)添加到FormData
  Object.keys(data).forEach(key => {
    formData.append(key, data[key]);
  });
  
  // 仅设置Authorization请求头,Content-Type由浏览器自动处理
  const headers = new HttpHeaders().set('Authorization', `Token ${localStorage.getItem('token')}`);
  const options = { headers };
  
  return this.http.post(url, formData, options).pipe(catchError(this.handleError<any>()));
}

Django端确认配置

如果使用DRF的ModelViewSet或CreateAPIView,默认已经支持multipart/form-data请求,无需额外配置。若自定义视图,确保视图类的parser_classes包含MultiPartParser和FormParser(DRF默认已包含这两个解析器)。

内容的提问来源于stack exchange,提问作者Victor Alarcon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 14:31:51