2012-04-21 68 views
1

目前我正在从ftp服务器将文件保存到loal目录。但我想转移到使用ImageFields使事情更易于管理。如何从Django的FTP下载保存到ImageField

这里是当前的代码片断

file_handle = open(savePathDir +'/' + fname, "wb")    
nvcftp.retrbinary("RETR " + fname, _download_cb) 
file_handle.close()  
return savePathDir +'/' + fname 

这是我在匹配的第一次尝试。我现在为了兼容性而返回路径。稍后我将通过模型正确访问存储的文件。

new_image = CameraImage(video_channel = videochannel,timestamp = file_timestamp) 
file_handle = new_image.image.open() 
nvcftp.retrbinary("RETR " + fname, _download_cb) 
file_handle.close() 
new_image.save() 
return new_image.path() 

这是正确的吗? 我很困惑我应该处理file_handle和ImageField的“图像”的顺序

+0

什么是_download_cb?你如何以及在哪里与'file_handle'交互? – ilvar 2012-04-21 04:09:28

回答

1

您错过了_download_cb,所以我没有使用它。
参考号The File Object of Django。尝试

# retrieve file from ftp to memory, 
# consider using cStringIO or tempfile modules for your actual usage 

from StringIO import StringIO 
from django.core.files.base import ContentFile 
s = StringIO() 
nvcftp.retrbinary("RETR " + fname, s.write) 
s.seek(0) 
# feed the fetched file to Django image field 
new_image.image.save(fname, ContentFile(s.read())) 
s.close() 

# Or 
from django.core.files.base import File 
s = StringIO() 
nvcftp.retrbinary("RETR " + fname, s.write) 
s.size = s.tell() 
new_image.image.save(fname, File(s))