Can I upload an object in memory to FTP using Python?

梦想与她 提交于 2019-11-28 05:09:08

问题


Here's what I'm doing now:

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')

Writing files to disk and then imediately deleting them seems like extra work on the system that should be avoided. Can I upload an object in memory to FTP using Python?


回答1:


Because of duck-typing, the file object (f in your code) only needs to support the .read(blocksize) call to work with storbinary. When faced with questions like this, I go to the source, in this case 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()

As commented, it only wants a file-like object, indeed it not even be particularly file-like, it just needs read(n). StringIO provides such "memory file" services.




回答2:


import urllib
import ftplib

ftp = ftplib.FTP(...)
f = urllib.urlopen('http://localhost/image.jpg')
ftp.storbinary('STOR image.jpg', f)



回答3:


You can use any in-memory file-like object, like BytesIO:

from io import BytesIO

It works both in binary mode with FTP.storbinary:

f = BytesIO(b"the contents")
ftp.storbinary("STOR /path/file.txt", f)

as well as in ascii/text mode with FTP.storlines:

f = BytesIO(b"the contents")
ftp.storlines("STOR /path/file.txt", f)

For more advanced examples, see:

  • Python - Upload a in-memory file (generated by API calls) in FTP by chunks
  • Python - Transfer a file from HTTP(S) URL to FTP/Dropbox without disk writing (chunked upload)
  • How to send CSV file directly to an FTP server


来源:https://stackoverflow.com/questions/2671118/can-i-upload-an-object-in-memory-to-ftp-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!