我有一个脚本可以将文件发送到 anonfiles.com 以使用 requests
进行共享。它模拟建议的 curl
命令:
curl -F "file=@test.txt" https://api.anonfiles.com/upload
with open(filename, 'rb') as file:
req = requests.post(
'https://api.anonfiles.com/upload',
files={'file': file},
)
res = json.loads(req.text)
这适用于小于 2GB 的文件,但是当文件变大时,它开始打印有关文件大小的错误消息。
我尝试使用 requests-toolbelt
发送文件但没有成功。
with open(filename, 'rb') as file:
encoder = MultipartEncoder({'file': file})
req = requests.post(
'https://api.anonfiles.com/upload',
data=encoder,
headers={'Content-Type': encoder.content_type}
)
res = json.loads(req.text)
从 anonfiles.com 返回以下错误:
{
"status": false,
"error": {
"message": "No file chosen.",
"type": "ERROR_FILE_NOT_PROVIDED",
"code": 10
}
}
我可能遗漏了一些明显的东西,但现在无法弄清楚。
P.S.:requests-toolbelt.MultipartEncoder
的使用不是强制性的,我试过了,但没有成功。即使不包括这个,我也会接受任何答案。没有 request
的解决方案不是最佳的,但也可以工作。
答案 0 :(得分:0)
使用元组似乎有效:
with open(filename, 'rb') as file:
encoder = MultipartEncoder({'file': (filename, file)})
req = requests.post(
'https://api.anonfiles.com/upload',
data=encoder,
headers={'Content-Type': encoder.content_type}
)
res = json.loads(req.text)
答案 1 :(得分:-1)
编辑:
经过进一步检查,我真的不确定发生了什么。我最初认为您可以通过随请求发送 json=json_file 来修复它,但后来我意识到您正在使用编码器。我不知道 MultipartEncoder 是否会以与 json 对象相同的方式工作。
无论如何...祝你好运!
我认为这是 json.load
与 json.loads
的一个简单案例:
json.load
用于 files
json.loads
用于 strings
在您的原始代码中,您从未加载过文件,因为您使用了 json.loads
,它用于字符串。
虽然我无法解释为什么它适用于较小的文件,所以也许我只是偏离了基地!!您也可以尝试对较大的文件进行某种流式传输。
我之前没有看到您用于响应的语法,所以我稍微重写了它以简化它以更好地理解它,但主要是我认为问题是我上面写的:
url = 'www.url.com'
headers = 'header stuff'
with open(filename, 'rb') as file:
json_file = json.load(file)
encoder = MultipartEncoder({'file': json_file})
response = requests.post(url, data=encoder, headers=headers).text
# or instead of appending .text you could create
# data = response.text for easier use in the rest of your code.