Reputation: 26336
I can read in a local file like so, but how can I now get the local file represented as a data url? I can't see any method for doing so.
This is a data url: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
import urllib.request
import random
import os
filename = urllib.request.pathname2url(random.choice(os.listdir('./sampledocuments')))
print(filename)
r = urllib.request.urlopen('file:///Users/myusername/sampledocuments/' + filename)
print(r)
print(r.info)
print(r.geturl)
print(dir(r))
Upvotes: 1
Views: 751
Reputation: 198344
Pretty straightforward: given mimetype
and data
,
import base64
...
f"data:{mimetype or ''};base64,{base64.b64encode(data).decode()}"
To get the data, you can modify your code as follows:
filename = random.choice(os.listdir('./sampledocuments'))
with open(filename, "rb") as f:
data = f.read()
Set the mimetype
if you know what it is, but it will work even if it's None
(it just may not do what you want).
Upvotes: 4