Search code examples
pythonsftpfastapi

Fast Api passing local file location to function to be upload to a server


I am making an endpoint with a fast API to upload multiple files in a single request.

To get multiple files use this.

   files: List[UploadFile] = File(...),

And i have another function that is responsible for uploading the files to an sftp:

    def save_to_sftp(self, file) -> str:
        hostname = "0.0.0.0"
        username = "foo"
        password = "pass"

        localfile = "/home/UserName/" + file.filename
        remotefile = "root/" + file.filename

        try:
            transport = paramiko.Transport(hostname, 22)
            transport.connect(username=username, password=password)
            sftp = paramiko.SFTPClient.from_transport(transport)

            sftp.put(localpath=localfile, remotepath=remotefile)
            sftp.close()
            transport.close()
            return file.filename
        except Exception as err:
            raise ValueError(err)

Now to upload the files to sftp I need the location of the file that will go to the server but until now I don't understand how I can do that.

I would like any suggestions on how I can send the local file location to my script or any suggestions on how I can get the files uploaded.

Thanks


Solution

  • Instead of using SFTPClient.put() use SFTPClient.putfo() which will copy the contents of a file-like object to the remote SFTP server.

    So your path operation function could do this:

    @app.post('/bulk/')
    async def bulk_upload(files: List[UploadFile] = File(...)):
        for file in files:
            save_to_sftp(file.file)
        return {'bulk_upload': 'OK'}
    

    And in save_to_sftp():

    sftp.putfo(file, remotepath=remotefile
    

    You might want to allow your save_to_sftp() function to accept a list of files to avoid creating multiple SFTP connections when there are several files to be saved.