2016-09-12 25 views
0

我无法将图像上传到服务器。所有属性都有图像。在request.FILES中,它们只是作为unicode数组的文件名。 而这个错误:Django + Ajax + FormData:上传的文件是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
在你的代码

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

尝试使用_f = request.FILES.get('your_parameter_name')来取代它

+0

是的,它的工作原理,我已经更新了我的问题,也许你可以改善我的代码,因为4.5MB图像了近300毫秒,以节省 –

+0

我认为它可能通过引起你的网络。但在本地主机上运行服务器? – mymusise

+0

是的,我认为这可能是由将文件保存到临时文件夹引起的。我的笔记本太慢了 –