如何使用 drf-chunked-upload 库将文件上传到服务器?
How do I upload files to the server using the drf-chunked-upload library?
我尝试了很多方法将文件上传到服务器,但我总是得到响应 {"detail": "No chunk file was submitted"}。如何正确使用这个库?
我的一个尝试:
import requests
url = 'http://127.0.0.1:8000/chunked_upload/'
in_file = open("testfile.txt", "rb")
data = in_file.read()
response = requests.put(
url,
headers={
"Content-Range": f"bytes {0}-{9}/{10}"
},
data={"filename": "testfile"},
files={'file': data},
)
打开文件并以块的形式向服务器重复发出 PUT 请求。
要完成上传,请使用文件的校验和发出 POST 请求。
例子
import hashlib
import os
import requests
from requests.auth import HTTPBasicAuth
auth = HTTPBasicAuth(username='username', password='password')
file = 'prova.txt'
size = os.path.getsize(file)
hash_md5 = hashlib.md5()
CHUNK_SIZE = 100
with open(file, 'rb') as f:
url = 'http://localhost:8000/'
offset = 0
for chunk in iter(lambda: f.read(CHUNK_SIZE), b''):
hash_md5.update(chunk)
res = requests.put(
url,
data={'filename': 'my_new_file'},
files={'file': chunk},
headers={
'Content-Range': f'bytes {offset}-{offset + len(chunk) -1}/{size}'
},
auth=auth
)
offset = int(res.json().get('offset'))
url = res.json().get('url')
finalize = requests.post(url, data={'md5': hash_md5.hexdigest()}, auth=auth)
print(finalize.status_code)
print(finalize.json())
我尝试了很多方法将文件上传到服务器,但我总是得到响应 {"detail": "No chunk file was submitted"}。如何正确使用这个库?
我的一个尝试:
import requests
url = 'http://127.0.0.1:8000/chunked_upload/'
in_file = open("testfile.txt", "rb")
data = in_file.read()
response = requests.put(
url,
headers={
"Content-Range": f"bytes {0}-{9}/{10}"
},
data={"filename": "testfile"},
files={'file': data},
)
打开文件并以块的形式向服务器重复发出 PUT 请求。 要完成上传,请使用文件的校验和发出 POST 请求。
例子
import hashlib
import os
import requests
from requests.auth import HTTPBasicAuth
auth = HTTPBasicAuth(username='username', password='password')
file = 'prova.txt'
size = os.path.getsize(file)
hash_md5 = hashlib.md5()
CHUNK_SIZE = 100
with open(file, 'rb') as f:
url = 'http://localhost:8000/'
offset = 0
for chunk in iter(lambda: f.read(CHUNK_SIZE), b''):
hash_md5.update(chunk)
res = requests.put(
url,
data={'filename': 'my_new_file'},
files={'file': chunk},
headers={
'Content-Range': f'bytes {offset}-{offset + len(chunk) -1}/{size}'
},
auth=auth
)
offset = int(res.json().get('offset'))
url = res.json().get('url')
finalize = requests.post(url, data={'md5': hash_md5.hexdigest()}, auth=auth)
print(finalize.status_code)
print(finalize.json())