2015-05-05 43 views
0

这是我上传,我在一个基于类视图定义图像的代码,损坏的图像上传的Django

def _handle_uploaded_file(self, request): 

     folder = settings.MEDIA_ROOT 
     uploaded_filename = request.FILES['img_fl'].name 

     BASE_PATH ='/home/admin1/Desktop/virtualenv-12.1.1/mapfied' 
     # create the folder if it doesn't exist. 
     try: 
      os.mkdir(os.path.join(BASE_PATH, folder)) 
     except Exception as e: 
      pass 

     # save the uploaded file inside that folder. 
     full_filename = os.path.join(BASE_PATH, folder, uploaded_filename) 

     fd = open(full_filename, 'wb') 

     file_content = ContentFile(request.FILES['img_fl'].read()) 

     try: 
      for chunk in file_content.chunks(): 
       fout.write(chunk) 
      fout.close() 
       html = "<html><body>SAVED</body></html>" 
       print(html) 
     except Exception as e: 
      print(e) 

图像文件保存得到纠正与名的位置,但它是corrupted.I我无法找到确切的原因,我在这里做错了什么?

+1

的缩进fout.close()似乎是错误的。另外,fout在使用前没有定义。 – Cheng

+0

@Cheng Yup你是对的,但这也不是纠正问题 –

回答

2

这是我从以前的项目有写上传文件到硬盘:

def view_handling_function(request): 
    for key, value in request.FILES.iteritems(): 
     full_path = ... 
     save_uploadfile_to_disk(full_path, value) 

def save_uploadfile_to_disk(full_path, file): 
    with open(full_path, 'w+') as destination: 
     for chunk in file.chunks(): 
      destination.write(chunk) 
1

我觉得既然你正在寻找二进制上传,你需要打开文件的可写二进制模式,其实际上是wb +

你也可以使用'with'关键字来整理一下;请参阅Django示例here。如果你将文件作为FileField(或派生类)持久保存,你可以提供'upload_to'函数,它返回你想要存储文件的完整路径和文件名。这会让框架为您处理文件io。

+0

感谢您的答复,请参阅我正在尝试ajax上传,'wb +'不适合我...我想一些小错误,使其损坏 –

+0

考虑到你的方法正在保存的东西,这可能不是ajax请求的问题...似乎更可能是你的python代码写出文件的方式的问题。如何检查两个文件的二进制比较看看他们实际上有多不同? –