SSH上传网络文件报错TypeError:预期str/bytes/路径对象而非_io.BytesIO
Hey there! Let’s sort out this SSH upload issue you’re facing with your BytesIO image data. That TypeError pops up because most SSH file transfer tools (like Paramiko’s SFTP client) expect either a local file path or raw bytes as input—they don’t directly accept a BytesIO stream when you use the standard put() method. Here’s how to fix it step by step:
First, let’s recap your scenario
I’m guessing your working local file upload code looks something like this:
import paramiko from io import BytesIO # Your existing SSH/SFTP setup that works for local files ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('your_server_ip', username='your_user', password='your_pass') sftp = ssh.open_sftp() # This works fine for local files sftp.put('local_image.jpg', '/remote/server/path/uploaded_image.jpg')
And when you tried uploading your BytesIO object directly like this, you hit the error:
# This throws TypeError: expected str, bytes or os.PathLike object, not _io.BytesIO image_stream = BytesIO(your_network_image_bytes) sftp.put(image_stream, '/remote/server/path/uploaded_image.jpg')
Solution 1: Use putfo() for file-like objects
Paramiko’s SFTP client has a putfo() method specifically designed for uploading file-like objects (like BytesIO). Just make sure to reset the stream’s position to the start first—otherwise you’ll upload an empty file!
# Reset the BytesIO pointer to the beginning (critical!) image_stream.seek(0) # Use putfo() instead of put() to upload the stream sftp.putfo(image_stream, '/remote/server/path/uploaded_image.jpg')
Solution 2: Read BytesIO to raw bytes and write directly
If you’re using an older version of Paramiko where putfo() isn’t available, you can read the BytesIO content into raw bytes and write it directly to the remote file:
# Reset pointer to start image_stream.seek(0) # Extract raw bytes from the stream image_data = image_stream.read() # Open the remote file in write-binary mode and write the bytes with sftp.file('/remote/server/path/uploaded_image.jpg', 'wb') as remote_file: remote_file.write(image_data)
Key Notes
- Always call
seek(0)on yourBytesIOobject before uploading. If you’ve read from the stream previously (e.g., to check its length), the pointer will be at the end, and you’ll upload nothing. - If you’re fetching the image from the web (e.g., via
requests.get()), you can directly use the response’s raw stream or convert it to aBytesIO—just remember theseek(0)step.
Hope this gets your image uploads working smoothly!
内容的提问来源于stack exchange,提问作者equallyhero

