From wechat api doc:
curl -F [email protected] "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"
Translate the command above to python:
import requests
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE'
files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)
Doc: https://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
Answer from kev on Stack OverflowFrom wechat api doc:
curl -F [email protected] "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"
Translate the command above to python:
import requests
url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE'
files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)
Doc: https://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
In case if you were to pass the image as part of JSON along with other attributes, you can use the below snippet.
client.py
import base64
import json
import requests
api = 'http://localhost:8080/test'
image_file = 'sample_image.png'
with open(image_file, "rb") as f:
im_bytes = f.read()
im_b64 = base64.b64encode(im_bytes).decode("utf8")
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
payload = json.dumps({"image": im_b64, "other_key": "value"})
response = requests.post(api, data=payload, headers=headers)
try:
data = response.json()
print(data)
except requests.exceptions.RequestException:
print(response.text)
server.py
import io
import json
import base64
import logging
import numpy as np
from PIL import Image
from flask import Flask, request, jsonify, abort
app = Flask(__name__)
app.logger.setLevel(logging.DEBUG)
@app.route("/test", methods=['POST'])
def test_method():
# print(request.json)
if not request.json or 'image' not in request.json:
abort(400)
# get the base64 encoded string
im_b64 = request.json['image']
# convert it into bytes
img_bytes = base64.b64decode(im_b64.encode('utf-8'))
# convert bytes data to PIL Image object
img = Image.open(io.BytesIO(img_bytes))
# PIL image object to numpy array
img_arr = np.asarray(img)
print('img shape', img_arr.shape)
# process your img_arr here
# access other keys of json
# print(request.json['other_key'])
result_dict = {'output': 'output_key'}
return result_dict
def run_server_api():
app.run(host='0.0.0.0', port=8080)
if __name__ == "__main__":
run_server_api()
Adding this reply if anyone needs it for future.
Please find the below code for sending image file in Python requests. Here logo is the keyword for an image file, which one of our servers accepts as an input. Hence 'logo' is given. Also, make sure you remove 'Content-type' from the headers.
response = requests.post(url,data=data,headers=headers, files={'logo':open("your_image_file.jpeg",'rb')})
I have found the solution, it is quite easy:
data = {'upload': ''}
I needed to pass the upload string in that way and voilà!
python - Submitting POST Request with Image - Stack Overflow
How upload image with python requests
Posting image using requests on python - Stack Overflow
Sending image over POST request with Python Requests - Stack Overflow
Videos
import requests
url = 'http://localhost:5000/xxxx'
files = {'image_file': open('test2.png', 'rb')}
requests.post(url, files=files)
On the receiving side you can use
f = request.files['image_file']
This f will be in the form of bytes, you will have to decode bytes in the form of image. To do that using opencv you can use the following code
npimg = np.fromstring(f.read(), np.uint8)
img = cv2.imdecode(npimg, cv2.IMREAD_ANYCOLOR)
This is next to impossible to give a good answer without knowing more detail; What the API endpoint will accept, what you've already tried, etc. However, this is generally how you would upload a file in requests:
with open("/file/path.jpg") as fhandle:
resp = requests.put("http://endpoint/address", data=fhandle.read(), headers={
"Content-Type": "{{ENTER_CONTENT_TYPE_HERE}}",
})
You can then access the status code from the 'resp' object to check success etc. The 'put' method is interchangeable with 'post' or whatever HTTP method you are using. I assume you are familiar with generally how to use the library.
Hi Flaskers,
I'm having difficulty receiving image on the Flask backend:
@auth_blueprint.route('/auth/check_image', methods=['POST'])
@cross_origin()
def check_image():
try:
image_given = request.files['photo'] # <-- image won't make it to Flask
img = Image.open(image_given.stream)
return jsonify({'status': 'OK', 'message': f'{img.width} {img.height}'})Kivy front-end:
img = {'file': ('photo': open(f'{self.image_path}/example.jpg', 'rb'))}
try:
response = requests.post('http://www.example.com/auth/check_image', files=img)
print(str(response.content, 'utf-8'))Error output:
<title>500 Internal Server Error</title> 03-02 17:06:26.295 15175 15678 I python : <h1>Internal Server Error</h1> 03-02 17:06:26.295 15175 15678 I python : <p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>
Error output from the backend:
"content":"400 Bad Request: The browser (or proxy) sent a request that this server could not understand.","status":"fail"
I've found this block of code that allegedly works:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/im_size", methods=["POST"])
def process_image():
file = request.files['image']
# Read the image via file.stream
img = Image.open(file.stream)
return jsonify({'msg': 'success', 'size': [img.width, img.height]})
if __name__ == "__main__":
app.run(debug=True)url = 'http://127.0.0.1:5000/im_size'
my_img = {'image': open('test.jpg', 'rb')}
r = requests.post(url, files=my_img)
# convert server response into JSON format.
print(r.json())I found the code here https://jdhao.github.io/2020/04/12/build_webapi_with_flask_s2/, strangely I'm getting status code 400 using it.
Thank you for any insight.