gpt4 book ai didi

python - django rest framework 3 ImageField发送ajax结果 “No file was submitted.”

转载 作者:太空狗 更新时间:2023-10-30 01:33:38 25 4
gpt4 key购买 nike

我有一个带有 Django Rest Framework 的 API 端点来上传图像。你能发现我做错了什么吗?

#models.py

class test(models.Model):
...
upload_path = 'upload/'
image = models.ImageField(upload_to=upload_path, null=True, blank=True)
...

#serializers.py

class TestSerializer(serializers.ModelSerializer):
image = serializers.ImageField(
max_length=None, use_url=True,
)
class Meta:
model = test
fields = ('id','name','image',...)

#views.py

@api_view(['GET', 'POST'])
def test_list(request, site_id, block_id):

....

if request.method == 'POST':
serializer = TestSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(
serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else :
return Response(status=status.HTTP_403_FORBIDDEN)

#js

function setimage() {
var $input = $("#js_teaser_img");
var fd = new FormData;

fd.append('image', $input.prop('files')[0]);

$.ajax({
url: '/api/....',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
alert(data);
}
});
}

result image: ["No file was submitted."] 0: "No file was submitted."

结果

Django REST Framework upload image: "The submitted data was not a file"

+

var reader = new FileReader();  
reader.onload = function(e) {
var img_local = e.target.result;
$('.js_img_src').attr('src', img_local);
$.post('/api/..../7/', {'image':img_local} , function( data ) {
console.log(data);
});
}
reader.readAsDataURL(file);

最佳答案

为了从客户端发送文件,您应该使用“multipart/form-data”(jQuery 将 contentType 设置为“application/x- www-form-urlencoded"而不是默认)。阅读关于 SO 的这个问题:Sending multipart/formdata with jQuery.ajax

关于 python 和 django rest 框架,您应该在 API View 中使用 MultiPartParser 和/或 FileUploadParser 并且文件上传的首选方法应该是“ put”,正如您在此处的引用中所见:http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser .

附言。如果您使用 django rest 框架,我强烈建议您使用 Angular 而不是 jQuery,因为它为 rest 服务提供了出色的集成……相信我更好! ;)

关于python - django rest framework 3 ImageField发送ajax结果 “No file was submitted.”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31026908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com