文件上传/下载接口与普通接口类似,但是有细微的区别。
如果需要发送文件到服务器,例如:上传文档、图片、视频等,就需要发送二进制数据,上传文件一般使用的都是 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()
本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕,E-mail:975644476@qq.com
本文链接:http://www.gawce.com/tnews/558.html