当前位置:首页 > 资讯 > 正文

文件上传/下载接口(超简单的教程来了)

文件上传/下载接口(超简单的教程来了)

文件上传/下载接口与普通接口类似,但是有细微的区别。

如果需要发送文件到服务器,例如:上传文档、图片、视频等,就需要发送二进制数据,上传文件一般使用的都是 Content-Type: multipart/form-data 数据类型,可以发送文件,也可以发送相关的消息体数据。

反之,文件下载就是将二进制格式的响应内容存储到本地,并根据需要下载的文件的格式来写文件名,例如:F:/合同文件.pdf。

Request URL: /createbyfile

Request Method: POST

Content-Type: multipart/form-data

file

File

文档文件

title

String

文档名称

fileType

String

文件类型:doc, docx, txt, pdf, png, gif, jpg, jpeg, tiff, html, rtf, xls, txt

文件上传接口参数与普通post请求一样,需要写成Key和Value模式,Key为参数名称file(也是组件的name属性),Value为一个元组(与普通接口不同的地方)

"file": (
"", # 元组第一个值为文件名称,没有则取None
open(r"F:pdf_file.pdf", "rb"), # 若第一个值非None,则取文件open打开的二进制流,否则直接写文件路径,如"F:pdf_file.pdf"
"pdf" # 文件类型
)
"file": (
None,
"F:pdf_file.pdf"
)
{
"title": "接口发起的文档",
"fileType": "pdf"
}
req = {
"url": "127.0.0.1/v2/document/createbyfile",
"method": "POST",
"headers": {},
"files": {"file": ("", open(r"F:pdf_file.pdf", "rb"), "pdf")},
"data": {
"title": "接口发起的文档",
"fileType": "pdf"
}
}

base_api.py

123456789import requests


class BaseApi:
    @staticmethod
    def requests_http(req):
        # ** 解包
        result = requests.request(**req)
        return result
from base_api import BaseApi


class Createbyfile:

    def createbyfile(self):
        req = {
            "url": "127.0.0.1/createbyfile",
            "method": "POST",
            "headers": {},
            "files": {"file": ("", open(r"F:pdf_file.pdf", "rb"), "pdf")},
            "data": {
                "title": "接口发起的文档",
                "fileType": "pdf"
            }
        }
        res = BaseApi().requests_http(req)
        assert res.status_code == 200
        res_json = res.json()
        return res_json["result"]["documentId"]


if __name__ == '__main__':
    Createbyfile().createbyfile()

Request URL:/download

Request Method:GET

contractId

Long

ID

ID

downloadItems

String[]

下载可选项,NORMAL(正文),ATTACHMENT(附件)

needCompressForOneFile

Boolean

是,默认单文件也压缩

当下载的文件仅一份时,是否压缩

from base_api import BaseApi
class Download:
    def download(self):
        req = {
            "url": "127.0.0.1/download",
            "method": "GET",
            "headers": {},
            "params": {
                "contractId": 2947403075747869536,
                "downloadItems": ["NORMAL"],
                "needCompressForOneFile": False
            },
        }
        res = BaseApi().requests_http(req).content # 注意“.content"获取返回内容
        # with open("F:/response.zip", "wb") as f:
        with open("F:/response.pdf", "wb") as f:
            f.write(res)
        return res


if __name__ == '__main__':
    Download().download()

最新文章