通过 POST 请求发送二进制图像 [英] Send binary image by POST request

查看:58
本文介绍了通过 POST 请求发送二进制图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试发布请求以将 img 上传到 https://pasteboard.co/,但我总是收到 500 响应,告诉我,有一个丢失的文件.

i am trying to do a post request to upload a img to https://pasteboard.co/, but i am always getting a 500 response which tells me, there is a missing file.

文件确实存在,路径正确,不知道问题出在哪里.

The file is really existing and the path is correct, i don't know where the problem is.

import mechanicalsoup

browser = mechanicalsoup.StatefulBrowser()
browser.set_user_agent(
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36')

response = browser.open('https://pasteboard.co/')

payload = {"file": open('C:/Users/Oli/Google Drive/IMG_20190616_153432.jpg', 'rb').read()}
response = browser.post('https://pasteboard.co/upload', payload)

它不是以下内容的重复:在 Python 请求中使用 POST 表单数据上传图片

Its not a dublicate of: Upload Image using POST form data in Python-requests

如果我像那里一样尝试相同的代码:

If i try the same code like there:

import requests
session = requests.Session()
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}
session.headers = headers


session.get('https://pasteboard.co/')

image_file_descriptor = open('C:/Users/Oli/Google Drive/IMG_20190616_153432.jpg', 'rb').read()
payload = {"file": image_file_descriptor}

a = requests.post('https://pasteboard.co/upload', files=payload, headers=headers)

我收到 502 Bad Gateway 错误.

I get a 502 Bad Gateway error.

推荐答案

我使用 requests 模块制作的试试这个代码:

I made it using requests module Try this code:

import requests
import json

header = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}
img_file = open(r'C:/Users/Oli/Google Drive/IMG_20190616_153432.jpg', 'rb')
header['Content-Type'] = 'multipart/form-data'
files = {'file': ('Image.jpg', img_file, 'image/jpeg', {'Expires': '10'}) }
res = requests.post('https://pasteboard.co/upload', files=files)
uploaded_image_name = json.loads(res.content.decode('utf-8'))['fileName']
print(f'New Link: https://pasteboard.co/{uploaded_image_name}')

如果您上传 png,只需更改以下内容:

if you upload a png just change the following things:

1.首先,

files = {'file': ('Image.png', img_file, 'image/png', {'Expires': '10'}) }

2.图片的路径.

检查这是否适合您.

这篇关于通过 POST 请求发送二进制图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆