簡體   English   中英

在 Python 請求中使用 POST 表單數據上傳圖像

[英]Upload Image using POST form data in Python-requests

我正在使用微信 API ...在這里我必須使用此 API http://admin.wechat.com/wiki/index.php?title=Transferring_Multimedia_Files將圖像上傳到微信服務器

url = 'http://file.api.wechat.com/cgi-bin/media/upload?access_token=%s&type=image'%access_token
files = {
    'file': (filename, open(filepath, 'rb')),
    'Content-Type': 'image/jpeg',
    'Content-Length': l
}
r = requests.post(url, files=files)

我無法發布數據

來自微信api文檔:

curl -F media=@test.jpg "http://file.api.wechat.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"

將上面的命令翻譯成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)

文檔: https ://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file

如果您要將圖像作為 JSON 的一部分與其他屬性一起傳遞,則可以使用以下代碼段。
客戶端.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)

服務器.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()

當我想從 Python 將圖像文件發布到休息 API(雖然不是微信 API)時,我遇到了類似的問題。 我的解決方案是使用“數據”參數以二進制數據而不是“文件”形式發布文件。 請求 API 參考

data = open('your_image.png','rb').read()
r = requests.post(your_url,data=data)

希望這適用於您的情況。

使用這個片段

import os
import requests
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
  name_img= os.path.basename(path_img)
  files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
  with requests.Session() as s:
    r = s.post(url,files=files)
    print(r.status_code)
import requests

image_file_descriptor = open('test.jpg', 'rb')
# Requests makes it simple to upload Multipart-encoded files 
files = {'media': image_file_descriptor}
url = '...'
requests.post(url, files=files)
image_file_descriptor.close()

不要忘記關閉描述符,它可以防止錯誤: 顯式關閉文件重要嗎?

讓 Rest API 將圖像從主機上傳到主機:

import urllib2
import requests

api_host = 'https://host.url.com/upload/'
headers = {'Content-Type' : 'image/jpeg'}
image_url = 'http://image.url.com/sample.jpeg'

img_file = urllib2.urlopen(image_url)

response = requests.post(api_host, data=img_file.read(), headers=headers, verify=False)

您可以使用設置為 False 的選項驗證來省略 HTTPS 請求的 SSL 驗證。

如果您有CURL ,那么您可以直接從 Postman 獲取請求

import requests

url = "your URL"

payload={}
files=[
  ('upload_file',('20220212235319_1509.jpg',open('/20220212235319_1509.jpg','rb'),'image/jpeg'))
]
headers = {
  'Accept-Language': 'en-US',
  'Authorization': 'Bearer yourToken'
}

response = requests.request("POST", url, headers=headers, data=payload, files=files)

print(response.text)

這對我有用。

import requests

url = "https://example.com"
payload={}
files=[
  ('file',('myfile.jpg',open('/path/to/myfile.jpg','rb'),'image/jpeg'))
]

response = requests.request("POST", url, auth=("my_username","my_password"), data=payload, files=files)
print(response.text)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM