Максим Стукало Максим Стукало - 2 months ago 16
Ajax Question

Django + Ajax + FormData: uploaded file is unicode array

I can't upload images to the server. All attributes there are until images. In request.FILES they are, but only as unicode array of file name.
And this error:

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


It's my view:

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


and it's 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');
}


How i can resolve it? I've tried post it via tastypie, but there i couldn't save image too, because of tastypie returned for me byte-file of this request

UPDATED CODE:

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

Answer

in your code for _f in request.FILES: _f is a unicode type what mean it's just a string.

try to use _f = request.FILES.get('your_parameter_name') to replace it