Permintaan - Unggah File

Pada bab ini, kita akan mengupload file menggunakan request dan membaca isi dari file yang diupload. Kita bisa melakukannya dengan menggunakanfiles param seperti yang ditunjukkan pada contoh di bawah ini.

Kami akan menggunakan http://httpbin.org/posting untuk mengunggah file.

Contoh

import requests
myurl = 'https://httpbin.org/post'
files = {'file': open('test.txt', 'rb')}
getdata = requests.post(myurl, files=files)
print(getdata.text)

Test.txt

File upload test using Requests

Keluaran

E:\prequests>python makeRequest.py
{
   "args": {},
   "data": "",
   "files": {
      "file": "File upload test using Requests"
   },
   "form": {},
   "headers": {
      "Accept": "*/*",
      "Accept-Encoding": "gzip, deflate",
      "Content-Length": "175",
      "Content-Type": "multipart/form-data; 
      boundary=28aee3a9d15a3571fb80d4d2a94bfd33",
      "Host": "httpbin.org",
      "User-Agent": "python-requests/2.22.0"
   },
   "json": null,
   "origin": "117.223.63.135, 117.223.63.135",
   "url": "https://httpbin.org/post"
}

Dimungkinkan juga untuk mengirim isi file seperti yang ditunjukkan di bawah-

Contoh

import requests
myurl = 'https://httpbin.org/post'
files = {'file': ('test1.txt', 'Welcome to TutorialsPoint')}
getdata = requests.post(myurl, files=files)
print(getdata.text)

Keluaran

E:\prequests>python makeRequest.py
{
   "args": {},
   "data": "",
   "files": {
      "file": "Welcome to TutorialsPoint"
   },
   "form": {},
   "headers": {
      "Accept": "*/*",
      "Accept-Encoding": "gzip, deflate",
      "Content-Length": "170",
      "Content-Type": "multipart/form-data; 
      boundary=f2837238286fe40e32080aa7e172be4f",
      "Host": "httpbin.org",
      "User-Agent": "python-requests/2.22.0"
   },
   "json": null,
   "origin": "117.223.63.135, 117.223.63.135",
   "url": "https://httpbin.org/post"
}