我有一个 POST API 视图,它接受图像和样式字符串并返回样式图像。 它在邮递员身上工作得很好,但我无法使用 fetch API 让它工作。
序列化器:
class GetImageSerializer(serializers.Serializer):
image = serializers.ImageField()
style = serializers.CharField()
DRF 视图:
class PostImage(APIView):
serializer_class = GetImageSerializer
parser_classes = [MultiPartParser]
def post(self,request,format=None):
print(request.data) # Debug
img = request.data.get('image')
# Process
response = FileResponse(img)
return response
获取调用:
json = {}
json["image"] = this.state.image
json["style"] = "models\\wave\\wave200.pth"
console.log("sending --- ",json) //debug
fetch('/style_transfer/style/',{
headers: { "Content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" },body: json,method: "POST"
}
).then(response => {
if (!response.ok) {
console.log("couldn't fetch image")
}
return response.json()
})
.then(data => {
console.log("fetched data")
console.log(data)
控制台日志的输出。这表明正确的数据在json字典中
但是数据没有被 DRF 服务器接收。
视图中的 print(request.data)
返回 <QueryDict: {}>
。
奇怪的是,同样的代码与邮递员一起工作。
我尝试过的事情:
- 从提取请求中移除
headers
- 这会引发不支持的媒体类型错误 - 将 content-type 设置为
"application/json"
- 这会读取字符串参数,但图像键为空。这就是request.data
的样子{'image': {},'style': 'models\\wave\\wave200.pth'}
我想了解导致此问题的原因。我已经阅读了几个类似的主题,但我找不到推荐的方法来做这样的事情。那么,有什么问题?推荐的做法是什么?