How to get file path from UploadFile in FastAPI?
Solution 1:
UploadFile uses Python's SpooledTemporaryFile, which is a "file stored in memory", and "is destroyed as soon as it is closed". You can either read the file contents (i.e., contents = await file.read())
and then upload these bytes to your server (if it permits), or copy the contents of the uploaded file into a NamedTemporaryFile, as explained here. Unlike SpooledTemporaryFile, NamedTemporaryFile "is guaranteed to have a visible name in the file system" that "can be used to open the file". The temp file's path can be accessed through file_copy.name
contents = await file.read()
file_copy = NamedTemporaryFile('wb', delete=False)
f = None
try:
# Write the contents to the temp file
with file_copy as f:
f.write(contents);
# Here, upload the file to your S3 service
f = open(file_copy.name, 'rb')
print(f.read(10))
finally:
if f is not None:
f.close() # Remember to close the file
os.unlink(file_copy.name) # delete the file