Django + Ajax + FormData:上传的文件是unicode数组

时间:2016-09-12 14:46:08

标签: ajax django polymer form-data

我无法将图像上传到服务器。所有属性都在图像之前。在request.FILES中它们是,但仅作为文件名的unicode数组。 这个错误:

AttributeError: 'unicode' object has no attribute 'read'

这是我的观点:

    for _f in request.FILES:
        print(_f)
        for _fi in _f:
            print(_fi)
        photo = PostPhoto.objects.create(photo = _f, name = str(_f))
        photo.save()

        destination = open('media/photos/'+str(photo.pk)+'.jpeg', 'w')
        for chunk in _f.read():
            destination.write(chunk)
        destination.close()

        print(photo)

        post.photos = photo

并且是js:

                    if (file.length <= 10) {
                        if (hasExtension(file, ['jpeg','jpg'])) {
                            console.log('files are correct');
                            var message = document.getElementById('search_textarea').value;
                            console.log('text');
                            var body_data = new FormData();
                            body_data.append('text', message);
                            body_data.append('loc_lat', elements[i].latitude);
                            body_data.append('loc_lon', elements[i].longitude);
                            body_data.append('loc_name', results[i].name);
                            body_data.append('loc_addr', results[i].formatted_address);
                            body_data.append('types', results[i].types);
                            body_data.append('action', null);
                            for(var k = 0; k <= (file.length - 1); k++) {
                                console.log(file[k]);
                                body_data.append(k, file[k], file[k].name);
                            }
                            this.$.ajaxNewPost.body = body_data;
                            this.$.ajaxNewPost.contentType = false;
                            this.$.ajaxNewPost.generateRequest();
                            console.log('ajax sended');
                        } else {
                            console.log('incorrect files');
                        }
                    } else {
                        alert('too match files');
                    }

我如何解决它?我试过通过tastypie发布它,但是我也无法保存图像,因为tastypie为我返回了此请求的字节文件

更新后的代码:

    for _f in request.FILES:
        photo = PostPhoto.objects.create(photo=_f, name=str(_f))
        photo.save()

        destination = open('media/photos/' + str(photo.pk) + '.jpeg', 'w')
        for _file in request.FILES.get(_f):
            for chunk in _file:
                destination.write(chunk)

        post.photos = photo
        destination.close()

1 个答案:

答案 0 :(得分:1)

代码中的

for _f in request.FILES: _f是一个unicode类型,它只是一个字符串。

尝试使用_f = request.FILES.get('your_parameter_name')替换它