2012-04-21 36 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))