fsc*_*kin 3 python ftp upload object ftplib
这就是我现在正在做的事情:
mysock = urllib.urlopen('http://localhost/image.jpg')
fileToSave = mysock.read()
oFile = open(r"C:\image.jpg",'wb')
oFile.write(fileToSave)
oFile.close
f=file('image.jpg','rb')
ftp.storbinary('STOR '+os.path.basename('image.jpg'),f)
os.remove('image.jpg')
Run Code Online (Sandbox Code Playgroud)
将文件写入磁盘然后立即删除它们似乎是应该避免的系统上的额外工作.我可以使用Python将内存中的对象上传到FTP吗?
由于鸭子类型,文件对象(f在您的代码中)只需要支持.read(blocksize)调用storbinary.当面对这样的问题时,我会转到源代码,在本例中为lib/python2.6/ftplib.py:
def storbinary(self, cmd, fp, blocksize=8192, callback=None):
"""Store a file in binary mode. A new port is created for you.
Args:
cmd: A STOR command.
fp: A file-like object with a read(num_bytes) method.
blocksize: The maximum data size to read from fp and send over
the connection at once. [default: 8192]
callback: An optional single parameter callable that is called on
on each block of data after it is sent. [default: None]
Returns:
The response code.
"""
self.voidcmd('TYPE I')
conn = self.transfercmd(cmd)
while 1:
buf = fp.read(blocksize)
if not buf: break
conn.sendall(buf)
if callback: callback(buf)
conn.close()
return self.voidresp()
Run Code Online (Sandbox Code Playgroud)
如评论所述,它只需要一个类似文件的对象,实际上它甚至不是特别类似于文件,它只是需要它read(n).StringIO提供这种"内存文件"服务.