将图像文件上传到服务器

时间:2017-03-13 20:05:16

标签: python django python-2.x

将uploar文件映像到服务器有一点问题

这是ajax发送文件到服务器的JS代码

/ **      *      * Init Crope图像      *      * /

    $('input[type=file]').change(function(){
        files = this.files;
    });

    $('#upload_photo').click(function (event) {
        event.stopPropagation(); // Остановка происходящего
        event.preventDefault();  // Полная остановка происходящего

        var data = new FormData();
        $.each( files, function( key, value ){
            data.append( key, value );
        });

        var obj = {
            csrfmiddlewaretoken: $('input[name^="csrfmiddlewaretoken"]').val(),
            action: 'upload_photo',
            file: data
        };

        $.ajax({
            url: /user_ajax_set_photo/,
            type: 'POST',
            data: data,
            cache: false,
            dataType: 'json',
            processData: false,
            contentType: false,
            success: function( response, textStatus, jqXHR ){

                if( response.error === 'false' ){

                    console.log('Загружен' + response.error );

                }
                else{
                    console.log('ОШИБКИ ОТВЕТА сервера: ' + response.error );
                }
            },
            error: function( jqXHR, textStatus, errorThrown ){
                console.log('ОШИБКИ AJAX запроса: ' + textStatus );
            }
        });
    });
}

我们的观点

def user_ajax_set_photo(request):
    if request.method == 'POST':
        form = FileUploadForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            print 'valid form'
        else:
            print 'invalid form'
            print form.errors
    return True

最后那是我的表格

class FileUploadForm(forms.Form):

    class Meta:
        model = RegModel
        fields = ['image']

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request", None)
        super(FileUploadForm, self).__init__(*args, **kwargs)

    def save(self):
        photo = super(FileUploadForm, self).save(commit=False)
        artist = RegModel.objects.get(id=self.request.user.id)
        photo.artist = artist
        photo.save()
        return photo

你能告诉我我的演出在哪里......

来自backtrase的最后错误

AttributeError: 'bool' object has no attribute 'get'

1 个答案:

答案 0 :(得分:1)

这里的问题是你的视图必须返回某种Django Response对象。鉴于你在这里使用AJAX,我猜你想要使用JSONResponse对象:

from django.http import JSONResponse

def user_ajax_set_photo(request):
    if request.method == 'POST':
        form = FileUploadForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            print 'valid form'
        else:
            print 'invalid form'
            print form.errors
    return JSONResponse([True], safe=False)

请注意,在JSON中,您不能只有浮动布尔值,因此我将其包装在数组中。默认情况下,当您将非dict对象传递给JSONResponse时,您还必须传递safe=False