Search code examples
pythonfilefile-uploadsqlalchemyfastapi

sqlalchemy-file package FileField is not allowing to give custom filename, automatically saves the file as unnamed


I am using sqlalchemy-file package FileField to save files in local storage, it is being saved but not allowing to give custom filename, automatically saves the file as unnamed. I need to fix that.

I am working on FastAPI project and using file variable as shown below to save files

from sqlalchemy_file import FileField

class UserDoc(Base):
    __tablename__ = "user_doc"

    id = Column(Integer, primary_key=True)
    file = Column(FileField)

this is how I save the file

@router.post(
    "doc_upload"
)
async def document_upload(
    user_file: UploadFile = File(...),
    db: Session = Depends(deps.get_db),
):
    try:
        # code logic
        file_contents = await user_file.read()
        document_data = {"file": file_contents}
        db_document = UserDocument(**document_data)
        db.add(db_document)
        db.commit()
        db.refresh(db_document)
    except Exception as _:
        # exception logic

the file contents are stored in the database as

{
   "content_path":null,
   "filename":"unnamed",
   "content_type":"application/octet-stream",
   "size":267226,
   "files":[
      "upload_folder/121e7cbf-f19c-4538-8fcf-2f323f31e53e"
   ],
   "file_id":"121e7cbf-f19c-4538-8fcf-2f323f31e53e",
   "upload_storage":"upload_folder",
   "uploaded_at":"2024-04-19T05:21:35.429745",
   "path":"upload_folder/121e7cbf-f19c-4538-8fcf-2f323f31e53e",
   "url":"/base_path/upload_folder/121e7cbf-f19c-4538-8fcf-2f323f31e53e",
   "saved":true
}

so when i try to download the file it is giving me unnamed, I want to save it with a name.


Solution

  • You have to use sqlalchemy_file.File like File(content=file_contents, filename="some file name here")

    To what you already have, make that change.

    from sqlalchemy_file import File
    
    file_contents = await user_file.read()
    
    document_data = {"file": File(content=file_contents, filename="some file name here")}
    db_document = UserDocument(**document_data)
    db.add(db_document)
    db.commit()