I have an endpoint that allows users to upload files. I would like to rename the file to a random and unique file name but can't work out how to change the filename. My current code is as follows which is saving the file to files/filename
@router.post('/qualifications/file')
async def create_file(files: UploadFile = File(...)):
file_location = f"files/{files.filename}"
with open(file_location, "wb+") as file_object:
file_object.write(files.file.read())
return {"info": f"file '{files.filename}' saved at '{file_location}'"}
Can you generate a custom file location instead of using files.filename? You may have to work out what the files.filename extension was and pass that into the new file_name you are creating.
@router.post('/qualifications/file')
async def create_file(files: UploadFile = File(...)):\
file_name = "some_random_name.txt"
file_location = f"files/{file_name}"
with open(file_location, "wb+") as file_object:
file_object.write(files.file.read())
return {"info": f"file '{file_name}' saved at '{file_location}'"}