python-上传下载文件

接口方式:

 

一、服务端接口

复制代码

import flask, os,sys,time
from flask import request, send_from_directory

interface_path = os.path.dirname(__file__)
sys.path.insert(0, interface_path)  #将当前文件的父目录加入临时系统变量


server = flask.Flask(__name__)


#get方法:指定目录下载文件
@server.route('/download', methods=['get'])
def download():
    fpath = request.values.get('path', '') #获取文件路径
    fname = request.values.get('filename', '')  #获取文件名
    if fname.strip() and fpath.strip():
        print(fname, fpath)
        if os.path.isfile(os.path.join(fpath,fname)) and os.path.isdir(fpath):
            return send_from_directory(fpath, fname, as_attachment=True) #返回要下载的文件内容给客户端
        else:
            return '{"msg":"参数不正确"}'
    else:
        return '{"msg":"请输入参数"}'


# get方法:查询当前路径下的所有文件
@server.route('/getfiles', methods=['get'])
def getfiles():
    fpath = request.values.get('fpath', '') #获取用户输入的目录
    print(fpath)
    if os.path.isdir(fpath):
        filelist = os.listdir(fpath)
        files = [file for file in filelist if os.path.isfile(os.path.join(fpath, file))]
    return '{"files":"%s"}' % files


# post方法:上传文件的
@server.route('/upload', methods=['post'])
def upload():
    fname = request.files.get('file')  #获取上传的文件
    if fname:
        t = time.strftime('%Y%m%d%H%M%S')
        new_fname = r'upload/' + t + fname.filename
        fname.save(new_fname)  #保存文件到指定路径
        return '{"code": "ok"}'
    else:
        return '{"msg": "请上传文件!"}'


server.run(port=8000, debug=True)

复制代码

 

二、客户端发送请求

复制代码

import requests
import os


#上传文件到服务器
file = {'file': open('hello.txt','rb')}
r = requests.post('http://127.0.0.1:8000/upload', files=file)
print(r.text)


#查询fpath下的所有文件
r1 = requests.get('http://127.0.0.1:8000/getfiles',data={'fpath': r'download/'})
print(r1.text)


#下载服务器download目录下的指定文件
r2 = requests.get('http://127.0.0.1:8000/download',data={'filename':'hello_upload.txt', 'path': r'upload/'})
file = r2.text #获取文件内容
basepath = os.path.join(os.path.dirname(__file__), r'download/')
with open(os.path.join(basepath, 'hello_download.txt'),'w',encoding='utf-8') as f: #保存文件
    f.write(file)

复制代码

 

非接口方式:

 

def upload(filename):
    #buld post body data
    boundary = '--xxxxxxxxxxxxxxxx '       http_url='http://xx.xx.com/upload.php'
    data = []
    data.append('--%s' % boundary)
    
    fp=open(filename,'rb')
    data.append('Content-Disposition: form-data; name="%s"; filename="%s"' % ('file',filename))
    data.append('Content-Type: %s\r\n' % 'text/html')
    data.append(fp.read())
    fp.close()
    data.append('--%s--\r\n' % boundary)

    http_body = '\r\n'.join(data)
    try:
        req = urllib2.Request(http_url, data=http_body)
        req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
        res = urllib2.urlopen(req, timeout=5)
        print res.read().decode('utf8')
    except Exception,e:
        print 'Error: %s' % e

复制代码


再补充一下用html上传文件到服务器

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

<head>

    <link rel="shortcut icon" href="favicon.ico">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>导入数据</title>

    <script type="text/javascript">

    function check(form) {

        if(form.file.value==''){

            alert('请选择要上传的文件!');

            form.file.focus();

            return false;

        }

        return true;

    }

 

    window.onload = function() {

        document.form.reset();

    }

    </script>

</head>

 

<h1 align="center">导入数据</h1>

 

<fieldset>

    <legend><b>请选择要上传的文件: <b></legend>

    <form action="http://xx.xx.com/upload.php" method="post" name="form" enctype="multipart/form-data" onsubmit="return check(this);" target="result">

        <input type="file" name="file" size=50>

        <input type="submit" name="upload" value="上传">

    </form>

</fieldset>

 

<iframe name="result" frameborder=0 width="100%" height="100%" scrolling="no"></iframe>

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值