我正在嘗試使用 python 將檔案上傳到服務器。服務器的 API 必須接受該檔案以及一些其他引數。
這就是為什么我打開檔案,然后創建一個字典,其中包含檔案和 Web 應用程式接受的其他引數,然后對其進行編碼并使用該專案執行 POST 請求。
這是代碼:
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)
但是,我在此行中收到錯誤:response = request.urlopen(req, data=form_data)
服務器以500HTTP 狀態代碼回應。
這是我得到的錯誤訊息:
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 500:
500 個錯誤代碼可能意味著很多事情,我不知道如何進一步發展,因為我所做的一切似乎都在書中......
鑒于此處提供的資訊,有沒有人有經驗指導我找到一些潛在的解決方案?
編輯:我正在嘗試復制做同樣事情的作業 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>
uj5u.com熱心網友回復:
js 代碼正在執行 multipart/form-data 發布請求。
我不相信 urllib 支持 multipart/form-data,你可以使用 request 代替。
import requests
with open('README.md', 'rb') as f:
files = {"file": f}
upload_credentials = {
"descr": "testing",
"title": "READMEE.md",
"contentType": "text",
"editor": username,
}
r = requests.post("http://httpbin.org/post", files=files, data=upload_credentials)
print(r.status_code)
print(r.text)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/412674.html
標籤:
上一篇:POST內容在接待處為空
