django rest框架3 ImageField发送ajax结果“未提交文件". [英] django rest framework 3 ImageField send ajax result “No file was submitted.”

查看:101
本文介绍了django rest框架3 ImageField发送ajax结果“未提交文件".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

#models.py

  class test(models.Model):...upload_path ='上传/'图片= models.ImageField(upload_to = upload_path,null = True,空白= True)... 

#serializers.py

  Class TestSerializer(serializers.ModelSerializer):图像= serializers.ImageField(max_length = None,use_url = True,)类Meta:型号=测试字段=('id','name','image',...) 

#views.py

  @api_view(['GET','POST'])def test_list(请求,site_id,block_id):....如果request.method =='POST':序列化器= TestSerializer(data = request.DATA)如果serializer.is_valid():serializer.save()返回响应(serializer.data,status = status.HTTP_201_CREATED)别的:返回响应(serializer.errors,status = status.HTTP_400_BAD_REQUEST)别的 :返回响应(状态=状态.HTTP_403_FORBIDDEN) 

#js

  function setimage(){var $ input = $(#js_teaser_img");var fd = new FormData;fd.append('image',$ input.prop('files')[0]);$ .ajax({网址:"/api/....",数据:fd,processData:否,contentType:false,输入:"POST",成功:功能(数据){警报(数据);}});} 

结果图像:[未提交文件."] 0:未提交文件."

结果

DjangoREST框架上传图片:提交的数据不是文件"

+

  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上阅读此问题:使用jQuery.ajax发送multipart/formdata

关于python和Django rest框架,您应该在API视图中使用 MultiPartParser 和/或 FileUploadParser ,并且上载的首选方法应该是"",您可以在此处的参考资料中看到: http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser .

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

I have an API endpoint with Django Rest Framework to upload an image. Can you spot what I'm doing incorrectly?

#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."

result

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);

解决方案

From the client side in order to send files, you should use "multipart/form-data" (jQuery sets contentType as "application/x-www-form-urlencoded" instead by default). Read this question on SO: Sending multipart/formdata with jQuery.ajax

Regarding instead python and django rest framework, you should use MultiPartParser and/or FileUploadParser in your API view and the preferred method for fle upload should be "put", as you can see in the reference here: http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser.

ps. if you use django rest framework, I strongly encourage you to use Angular instead of jQuery, since it offers an excellent integration for rest services... trust me is FAR BETTER! ;)

这篇关于django rest框架3 ImageField发送ajax结果“未提交文件".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆