【发布时间】:2022-01-14 14:48:07
【问题描述】:
我必须将 js 代码转换为 python。 js 代码使用 fetch() 通过 POST 请求执行文件上传。 这是js代码:
<input type="file" />
<button onclick="upload()">Upload data</button>
<script>
upload = async() =>
{
const fileField = document.querySelector('input[type="file"]');
await uploadDoc(fileField.files[0] );
};
uploadDoc = async( file ) =>
{
let fd = new FormData();
fd.append( 'file', file );
fd.append( 'descr', 'demo_upload' );
fd.append( 'title', name );
fd.append( 'contentType', 'text' );
fd.append( 'editor', user );
let resp = await fetch( url, { method: 'POST', mode: 'cors', body: fd });
};
</script>
代码有效并符合此处提供的 fetch() 文档: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_a_file
现在当我尝试在 python 中重新创建它时,我得到一个 500 HTTP 状态代码 这是python代码:
from urllib import request
from urllib.parse import urlencode
import json
with open('README.md', 'rb') as f:
upload_credentials = {
"file": f,
"descr": "testing",
"title": "READMEE.md",
"contentType": "text",
"editor": username,
}
url_for_upload = "" #here you place the upload URL
req = request.Request(url_for_upload, method="POST")
form_data = urlencode(upload_credentials)
form_data = form_data.encode()
response = request.urlopen(req, data=form_data)
http_status_code = response.getcode()
content = response.read()
print(http_status_code)
print(content)
但这不起作用,我收到此错误:
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 500:
有 js 和 python 经验的人或许能看出 python 端出了什么问题,或者如何将 fetch() 函数转换为 python。
【问题讨论】:
-
您使用的是什么 API?
-
获取似乎是一个 multipart/form-data" 请求。也许看看这个问题stackoverflow.com/questions/12385179/…
-
@某公司网页应用的API。
-
@ikhvjs 我会调查的。谢谢!
标签: javascript python post file-upload fetch