I want to know if it's possible with fastAPI, to receive a file and to save it as a name ? I know that we have to use UploadFile to mention the file we're receiving but how to save it as a special name, like a random string, I don't know. Thanks for answering and reading !
Asked
Active
Viewed 25 times
0
-
Read the file with `await file.read()` and write it to a new file with `open(...) as f` and `f.write()` as you'd write any file in Python. Make sure to write it to a safe path and do not trust the file name given by the client. – MatsLindh Nov 06 '22 at 20:19
-
@MatsLindh Is the function write() for saving a file as a name ? I want to save it but also as a name. – Nov 07 '22 at 09:07
-
`open(
)` is the plain Python function for opening a file. You then write content to that file. The path contains the file name as its last value (i.e. `/path/foo/bar.txt`). – MatsLindh Nov 07 '22 at 09:15 -
Can I change the file name? @MatsLindh – Nov 07 '22 at 09:16
-
Yes. The file will be written to whatever name you give to the `open` function. https://docs.python.org/3/library/functions.html#open – MatsLindh Nov 07 '22 at 10:27