阅读PDF并通过FTP在Python中发送

时间:2015-08-12 12:00:36

标签: python urllib2 ftplib

用例:我正在尝试从url读取pdf,然后通过FTP发送

我的功能如下:

index

----------------------------------------------- ------------------------------

def send_via_ftp(self, url, filename, ftp_site, username, password, directory):

    import urllib2
    try:
        data = urllib2.urlopen(url)
    except urllib2.URLError, e:
        print "Failed to fetch content: %s" % e
        return False
    except urllib2.HTTPError, e:
        print "HTTP ERROR: %s" % e
        return False

    return self.send_file_by_ftp(data, ftp_site, username, password, directory, filename)

我的电话看起来像: send_via_ftp(“http://url/ ***。pdf”,“XYZ.pdf”,“ftp url 192.168.0.101”,“XXXX”,“YYYYY”,“”)

文件在FTP文件夹中成功完成,但文件中的内容未写入。当我打开它时说“格式错误:不是pdf或损坏”。 可能是什么问题呢?非常感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您似乎将data作为第二个参数传递给remote_ftp_connection.storbinary,但它应该是ftp_data。不确定为什么你没有得到NameError例外。

答案 1 :(得分:0)

由于FTP使用类似文件的对象,因此以下修改对我有效。

def send_via_ftp(self, url, filename, ftp_site, username, password, directory):

import urllib2
try:
    from cStringIO import StringIO
except:
    from StringIO import StringIO

try:
    data = urllib2.urlopen(url)
    data_ = StringIO(data.read())
    data_.seek(0)
except urllib2.URLError, e:
    print "Failed to fetch content: %s" % e
    return False
except urllib2.HTTPError, e:
    print "HTTP ERROR: %s" % e
    return False
else:
    content = data_.read()

return self.send_file_by_ftp(content, ftp_site, username, password, directory, filename)

=============================================== =================================

def send_file_by_ftp(self, data, ftp_site, username, password, directory, filename):          

    import ftplib
    try:
        from cStringIO import StringIO
    except:
        from StringIO import StringIO
    try:
        remote_ftp_connection = ftplib.FTP(ftp_site)
    except ftplib.all_errors as e:
        print str(e)
        return False
    else:
        remote_ftp_connection.login(username, password)
        try:
            if len(directory):
                remote_ftp_connection.cwd(directory)
            remote_ftp_connection.storbinary("STOR %s" % filename, StringIO(data))
        except ftplib.error_perm,e:
            print str(e)
            return False
        else:
            remote_ftp_connection.quit()
            return True