requests--文件上传,文件下载

简介: requests--文件上传,文件下载

文件上传


在做接口自动化的时候,有时需要上传文件,比如更改头像等等,在request里,通过files参数来上传

import requests
base_url = 'http://httpbin.org'
file = {'file': open(r'E:\00.jpg', 'rb')}
r = requests.post(base_url + '/post', files=file)
print(r.text)


文件下载


第一种方式

import requests
def dowload_file(file_path):
    headers = {"Referer": "https://xx315.xx315.nex"}
    cookie = {"Cookie": "ASP.NET_SessionId=bij"}
    r = requests.get(url='https://xx315.xx315',
                     cookies=cookie,
                     headers=headers,
                     stream=True)
    if r.status_code == 200:
        with open(file_path, 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024):
                f.write(chunk)
dowload_file('F:\\123.xlsx')

注意:

文件如果不存在,会在当前目录下生成一个文件,有内容会清空在写入

第二种方式

import requests
import shutil
def download_file_raw(file_path):
    url = 'https://xx315.xx315.net/Ashx/Export'
    cookie = {"Cookie": 'ASP.NET_SessionId=sjl8'}
    r = requests.get(url=url,
                     cookies=cookie,
                     stream=True
                     )
    if r.status_code == 200:
        with open(file_path, 'wb') as f:
            r.raw.decode_content = True
            shutil.copyfileobj(r.raw, f)
download_file_raw('F:\\123.xlsx')

相关文章
|
前端开发 JavaScript 应用服务中间件
multer实现文件上传功能全解(form上传、fetch请求上传、多文件上传)
multer实现文件上传功能全解(form上传、fetch请求上传、多文件上传)
multer实现文件上传功能全解(form上传、fetch请求上传、多文件上传)
|
2月前
|
Java
Struts文件上传与下载详解_上传单个文件
Struts文件上传与下载详解_上传单个文件
10 0
|
2月前
|
Java
Struts文件上传与下载详解 _上传多个文件
Struts文件上传与下载详解 _上传多个文件
19 0
|
5月前
|
小程序 应用服务中间件 Shell
laravel8(三)文件上传提示 “The file deos not exits ” ,但确实已经上传了文件
Laravel 文件上传提示 “The file "" deos not exits ” ,但确实已经上传了文件
38 1
|
6月前
|
存储 前端开发 Java
SpringMVC的文件上传&文件下载&多文件上传---详细介绍
SpringMVC的文件上传&文件下载&多文件上传---详细介绍
42 0
|
9月前
|
前端开发
jmeter--文件上传
jmeter--文件上传
jmeter--文件上传
|
11月前
|
前端开发 Java Apache
文件上传与下载
文件上传与下载 文件上传也称为upload,是指将本地图片、视频、音频等文件上传到服务器上,可以供其他用户浏览或下载的过程。文件上传在项目中应用非常广泛,我们经常发微博、发微信朋友圈都用到了文件上传功能。 文件上传时,对页面的form表单有如下要求: method=“post” 采用post方式提交数据 enctype=“multipart/form-data” 采用multipart格式上传文件 type=“file” 使用input的file控件上传
servlet文件下载及上传
servlet文件下载及上传
96 0