Python 实现http server接收mutipart/form-data文件 方法1
- 1 Server端代码
- 2 客户端截图
- 3 代码说明
1 Server端代码
import os
from flask import Flask, request
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'E://recv//'
@app.route('/seenton/monitor/alarmImage', methods=['POST'])
def upload_file():
head = request.headers
print(f' recvvvvvvv head= [{head}]')
content_type = request.content_type
print(f' recvvvvvvv content_type= [{content_type}]')
boundary = request.content_type.split(';')[1].split('=')[1]
print(f' recvvvvvvv boundary= [{boundary}]')
content_len = request.content_length
if 'file' not in request.files:
return 'No file part'
file = request.files['file']
if file.filename == '':
return 'No selected file'
print(f' file.filename= [{file.filename}]')
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return 'File saved successfully'
if __name__ == '__main__':
app.run(host='192.168.1.173', port=18098)
2 客户端截图
PostMan生成Python 代码:
import requests
url = "http://192.168.1.16:18098/seenton/monitor/alarmImage"
payload = {}
files=[
('file',('测温点位1-58@stator#20220226-221220#stat.jpg',open('/D:/Desktop/20220226-221220-带双光融合效果/测温点位1-58@stator#20220226-221220#stat.jpg','rb'),'image/jpeg'))
]
headers = {}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
print(response.text)
3 代码说明
- 代码基本功能:实现将客户端发送的文件转发到本地。
- 代码中的打印:为了调试方便代码中增加了一些关于boudary的打印。
- 代码中的自定义字段:代码中的 ‘file’ 就是postman客户端请求中的文件名称。