使用Expo+Axios向Django Rest Framework传图片时遇400错误
解决Expo上传图片到Django API的400错误问题
以下是针对你代码的几个关键修复点,按优先级排查:
1. 修正FormData中图片的封装格式
Expo ImagePicker返回的图片对象不能直接传入FormData,需要构造包含uri、name、type的标准对象,确保Django能正确解析:
const postData = async () => { try { const formData = new FormData() // 正确封装图片参数 formData.append('image', { uri: image.uri, name: image.fileName || `post-image-${Date.now()}.jpg`, type: image.type || 'image/jpeg' }) formData.append('user', 2) formData.append('text', text) const resp = await authAxios.post('posts/', formData) console.log(resp.data) setText('') setImage(null) } catch (error) { // 打印Django返回的具体错误详情,快速定位问题 console.error('错误详情:', error.response?.data) } }
2. 移除手动设置的Content-Type头
手动设置"Content-Type": "multipart/form-data"会丢失自动生成的boundary分隔符,导致Django无法解析表单结构。axios会自动根据FormData生成包含boundary的正确Content-Type,直接删除该header配置即可。
3. 调整序列化器,排除只读关联字段
你的序列化器包含likes和comments两个ManyToMany字段,创建帖子时不需要传入这些字段,默认序列化器的验证逻辑会因此引发400错误。修改序列化器:
class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['user', 'text', 'image'] # 仅保留创建时需传入的字段 # 或者保留所有字段,将关联字段设为只读 # read_only_fields = ['likes', 'comments']
4. 确认Django的MEDIA配置(可选但必要)
确保项目已正确配置媒体文件存储路径,避免图片保存失败:
# settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # urls.py(开发环境) from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # 你的其他路由配置 ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
内容的提问来源于stack exchange,提问作者Cleiton Oliveira
相关产品推荐
相关产品推荐

