业务场景:
通常我们需要上传文件或者导入文件如何操作呢?
首先通过f12或者通过抓包查到请求接口的参数,例如:
图中标注的就是我们需要的参数,其中 name是参数名,filename是文件名,Content-Type是上传文件的类型,不管上传图片,视频,还是excel等文件类型,其参数都是这3种,将下面3个参数放在接口;
下面借助python+requests 通过接口实现文件上传:
import requests as requestsurl = 'https://uat.tangusoft.com:8443/tcmts2/warehouseIn/importWesternWarehouseIn'
files = {"file": ("recognizeChips_file", open(r"D:\tanggu\导入模板\西药入库_导入.xls", "rb"),"application/vnd.ms-excel")}
data = {"warehouseId": "46","dealDate": '2023-08-29',
}
authorization={"authorization":"Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIzMjEiLCJhdWQiOiJ3ZWIiLCJyb2xlIjpbeyJhdXRob3JpdHkiOiJST0xFXzI4In1dLCJuYW1lIjoiYWRtaW4iLCJleHAiOjE2OTM4NzkxMzYsImlhdCI6MTY5MzI3NDMzNiwidGVuYW50IjoidGNtdHMyIiwianRpIjoiMSJ9.0LQMlApGJcOBm1uzTZszaGM5wiE9ew7ue2WCwUwjqimiPaO39V4s6h80O72Vnpx74kwYoIfHLgH3yQ4w2OJE2w"
}
r = requests.post(url=url, headers=authorization, files=files, data=data)
print(r.text)
注意:在执行代码会出现以下错误:OSError: [Errno 22] Invalid argument
别着急,出现这个是因为平台的bug,像pycharm,Spyder等,复制黏贴路径都会报错
解决方法:
写路径的时候前面加上r
,r"file":意思是指为了避免\xx是一个转义字符而导致的错误,也就是说加上r之后,“”里的就不再出现转义字符,编程纯的文件地址。:
files = {"file": ("recognizeChips_file", open(r"D:\tanggu\导入模板\西药入库_导入.xls", "rb"),"application/vnd.ms-excel")}