我正在運行一個托管強制門戶的 Python HTTP 服務器。基本上我正在嘗試將受密碼保護的檔案上傳到服務器。現在我可以使用 JavaScript 和 FileReader 將檔案上傳到服務器。我就是這樣做的:
var file_cli_cert = document.getElementById(id="exa_cli_cert").files[0];
const xmlhttp1 = new XMLHttpRequest();
let name = file_cert.name;
let reader = new FileReader();
reader.readAsText(file_cert);
xmlhttp1.open("POST", '/load/cert');
reader.onload = function(){
xmlhttp1.send(name "&CERT=" reader.result);
對于不受密碼保護的檔案,這很有效。
對于受密碼保護的檔案,我的想法是獲取檔案和密碼以訪問資料。問題是我不知道如何在 JS 中訪問受密碼保護的檔案,我認為這是不可能的。所以現在我想知道如何將檔案和密碼發送到服務器并在那里訪問檔案資料。如果我使用 XMLHttpRequest.send() 發送檔案物件,則在服務器端我會以字串格式獲取物件。
要在服務器端閱讀 POST 訊息,我會:
ctype, pdict = cgi.parse_header(self.headers['content-type'])
content_len = int(self.headers.get('Content-length'))
post_body = self.rfile.read(content_len) #read credentials
self.send_response(201)
self.end_headers()
if self.path.endswith('/load/cert'): #if user loads a certificate
post_body = post_body.decode()
post_body = post_body.split("&CERT=") #split name and file content
name_cert = post_body[0]
file_content = post_body[1]
f = open("./certs/" name_cert, "w")
f.write(file_content)
f.close()
我是這方面的新手,我一直在尋找解決方案幾個小時。任何幫助將不勝感激。
uj5u.com熱心網友回復:
沒有 python 專家,但使用 FileReader 將加密檔案作為文本讀取可能會出現問題,因為在將其編碼為文本時可能會導致一些資料丟失。您應該將其作為二進制檔案使用reader.readAsArrayBuffer()
但是不需要將檔案的內容讀入記憶體并分配記憶體,只需將 blob/檔案直接上傳到服務器,它就會負責將資料從磁盤發送到網路,而無需接觸主 javascript 執行緒任何文本轉換。
const [ file ] = document.querySelector('#exa_cli_cert').files
fetch('/load/cert', {
method: 'POST',
body: file,
headers: {
'x-file-name': file.name
}
})
.then(r => r.arrayBuffer())
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/523061.html
