Advertisement
yudiwibisono

upload_file_fastapi

Jun 14th, 2023
689
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. from fastapi import File, UploadFile
  2. from fastapi.responses import FileResponse
  3.  
  4. #upload image
  5. @app.post("/uploadimage")
  6. # pip install python-multipart
  7. # buat terlebih dulu direktori /data_file untuk menyimpan file
  8. def upload(file: UploadFile = File(...)):
  9.     try:
  10.         print("mulai upload")
  11.         print(file.filename)
  12.         contents = file.file.read()
  13.         with open("./data_file/"+file.filename, 'wb') as f:
  14.             f.write(contents)
  15.     except Exception:
  16.         return {"message": "Error upload file"}
  17.     finally:
  18.         file.file.close()
  19.  
  20.     return {"message": f"Upload berhasil: {file.filename}"}
  21.  
  22. # ambil image berdasarkan nama file
  23. @app.get("/getimage/{nama_file}")
  24. async def getImage(nama_file:str):
  25.     return FileResponse("./data_file/"+nama_file)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement