2013-07-17 100 views
1

I working on a mobile application, where user can upload images, am using Django in server side.如何将图像保存到磁盘

我以两种方式获取图像,我想将图像保存到除外情况下的磁盘上。

imageFile = request.FILES['image'] 
try: 
    file_path = imageFile.temporary_file_path() 
except AttributeError as e: 
    logger.debug(virtualFile') 
    imageStringBuffer = imageFile.read() 
    virtualFile = StringIO.StringIO(imageStringBuffer) 
    # want to save the imageStringBuffer to disk 

I want to to save the 'virtualFile' (in except case) to the disk , How can I do it?

回答

2
def handle_uploaded_file(f): 
    with open('imgepath', 'wb+') as destination: 
     for chunk in f.chunks(): 
      destination.write(chunk) 

参考:here

+0

我试过使用它,但是图像无法打开。经过进一步调查,唯一保存在磁盘上的是上传文件的名称。有什么建议么? – AndrewSmiley

+0

我使用的只是一个示例图像位置,使用正确的。 – Jisson

+0

感谢您的回复。我一直在尝试从POST数据中获取图像,但这不起作用。对我的表单进行了一些调整,我可以将它从FILES变量中拉出来。你的代码在那个时候工作。 – AndrewSmiley

3

你不需要virtualFile。您已有imageStringBugger中的图像数据。因此:

with file('filename_to_save_to.png', 'wb') as f: 
    f.write(imageStringBuffer) 

就够了。

+0

我有错误 'UTF-8' 编解码器不能在位置0解码字节0xFF:无效的起始字节。 UnicodeDecodeError:'utf8'编解码器无法解码位置0中的字节0xff:无效的开始字节 – Jisson