I’m trying to send some form values including file via SocketIO
const handleSubmit = () => {
const formData = new FormData();
formData.append('num1', numbers.num1);
formData.append('num2', numbers.num2);
formData.append('file', file);
socket.emit('submit', {payload: formData});
};
In console.log()
I see
numbers.num1, numbers.num2, file: 1 1 File { name: "data.zip", lastModified: 1691230842633, webkitRelativePath: "", size: 1196056, type: "application/x-zip-compressed" }
Event on backend receives
{'payload': {}}
app = Flask(__name__)
socketio = SocketIO(app)
CORS(app)
socketio.init_app(
app,
cors_allowed_origins="*",
logger=True,
engineio_logger=True)
@socketio.on('submit')
def handle_submit(data):
...
if __name__ == '__main__':
socketio.run(app, debug=True)
Why the payload missing at the event handler?
UPD:
In Chrome I receive just {}
, in Firefox {'payload': {}}
UPD2:
The reason why the data is empty is FormData on FE which is empty after append()
. What’s causing such behavior?
To send multiple data, including a file, via the socket you can use a nested structure.
The following example shows you a possible variant, where file
, as in the tutorial mentioned above, corresponds to a file that was taken as the first element from a FileList of an input element.
socket.emit('submit',
{
num1: numbers.num1,
num2: numbers.num2,
file: {
name: file.name,
type: file.type,
size: file.size,
data: file
}
}
);
On the server side you get a dictionary that contains the file’s data as bytes.
Using a FormData object doesn’t really make sense here since you don’t want to send a form. To upload a file, check out this tutorial. A nested structure with additional data and information about the file is also possible.
@Detlef If I need to send file and several number values, should I emit 2 separate event to sent values in json and file as socket.emit(“upload”, files[0). I use the FormData to pass them together