如何使用python将文件上传到远程服务器

时间:2013-01-21 06:39:50

标签: python wsgi

我需要使用python-wsgi将文件上传到远程位置。 远程位置不是托管python应用程序的服务器,而是不同的服务器。

我尝试将文件上传到服务器,该文件正是应用程序主机。它成功了。

使用以下代码

            post = cgi.FieldStorage(fp=environ['wsgi.input'],environ=environ,keep_blank_values=True)
        self.msg = str(post)            

        try:
            fileitem = post['Filedata']
            if fileitem.file:
                filename = fileitem.filename.decode('utf8').replace('\\','/').split('/')[-1].strip()
                if not filename:
                    raise Exception('No valid filename specified')
                file_path = os.path.join(self.uploadpath, filename)
                # Using with makes Python automatically close the file for you
                counter = 0
                with open(file_path, 'wb') as output_file:
                    while 1:
                        data = fileitem.file.read(1024)
                        # End of file
                        if not data:
                            break
                        output_file.write(data)
                        counter += 1
                        if counter == 100:
                            counter = 0
            self.msg = "Uploaded Successfully !!!! "
        except:
            pass

但这是针对python应用程序托管的本地位置。 我在Google上搜索如何将文件上传到python中的远程位置。 但我找不到合适的解决方案。有人建议用python代码做scp。

更多..

假设有两个名为A和B的服务器。我的python-wsgi文件上传应用程序托管在服务器A上。在python-wsgi应用程序中有一个Web表单,用户在用户点击上传时按用户选择文件该文件需要上传到服务器B(已知位置)

任何人都知道使用python将文件上传到远程位置的方法或库吗?

提前致谢。

2 个答案:

答案 0 :(得分:2)

文件上传通常使用 enctype = multipart / form-data 实现为HTTP POST操作。

http://www.w3schools.com/tags/att_form_enctype.asp

在Python中,您可以使用请求模块以方便使用。

除此之外:你的问题很糟糕。

答案 1 :(得分:2)

对于HTTP,如果服务器端没有足够的对应物,你将没有机会在服务器上放置文件,即Python / Perl / PHP / Ruby /任何获取你提供的数据的脚本 HTTP POST - 请求并将其写入文件。我建议设置一个FTP服务器。这正是FTP的发明。

通常,大多数HTTP服务器也都有FTP。你如何将HTML文件放在服务器上? FTP是这样做的最小访问。这真的不难设置。

相关问题