简体   繁体   中英

How to convert base64 encoded string to file without disk I/O in Python (for HTTP requests)

I want to send a file through requests library in Python, it accepts file type input. Here is a piece of working code I've tested myself.

FILES = []
f = open('/home/dummy.txt', 'rb')
# f : <type 'file'>
FILES.append(('file', f))
response = requests.post(url = 'https://dummy.com/dummy', headers = {'some_header':'content'}, data={'some_payload':'content'}, files=FILES)

This works just fine, now I have a base64 encoded string I just got from my database

base64_string = "Q3VyaW91cywgYXJlbid0IHlvdT8="
FILES = []
f = convert_base64_to_file(base64_string, "dummy.txt")
# f : <type 'file'>
FILES.append(('file', f))
response = requests.post(url = 'https://dummy.com/dummy', headers = {'some_header':'content'}, data={'some_payload':'content'}, files=FILES)

I need the convert_base64_to_file (which is an imaginary method). How do I achieve this without any disk I/O?

My base64_string doesn't have a filename. How do I simulate the filename so that it behaves just like I open a file from my disk?

I need the http request to post this:

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="dummy.txt"
Content-Type: application/x-object

... contents of file goes here ...

That's why I need to specify the filename.

You can use the io module :

import io
FILES = {}
f = io.BytesIO()
FILES{'file'] = ("dummy.txt", f)
response = requests.post(url = 'https://dummy.com/dummy', headers = {'some_header':'content'}, data={'some_payload':'content'}, files=FILES)

Here is the convert_base64_to_file function:

import base64
import io
def convert_base64_to_file(data):
    return io.BytesIO(base64.b64decode(data))

To complete Megalng answer which solves half of my problem, we can add a name to the constructed file by doing this:

import base64
import io
def convert_base64_to_file(base64_string,filename):
    f = io.BytesIO(base64.b64decode(base64_string))
    f.name = filename
    return f

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM