function sendMessage(data) { {#const radioInput = form.check.value;#} const fileInput = document.getElementById("file"); const radioInput = document.getElementsByName('check') fileInput.addEventListener('change', (event) => { const file = event.target.files[0]; const reader = new FileReader(); reader.onload = (event) => { const fileData = event.target.result; const selectedValue = Array.from(radioInput).find(input => input.checked).value; const data = { file: fileData, option: selectedValue }; {#return data#} console.log("开始传") console.log(selectedValue) console.log(fileData) {#console.log(fileData)#} socket.send(JSON.stringify(data)); }; reader.readAsArrayBuffer(file); }); } 传到socket中file只有{},
时间: 2024-02-14 22:29:18 浏览: 294
从你提供的代码来看,问题可能出在文件数据的传递上。在 JavaScript 中,`FileReader` 的 `readAsArrayBuffer()` 方法是异步的,所以你需要确保在读取完成后再将数据发送到服务器。
你可以尝试将发送数据的逻辑放在 `reader.onload` 的回调函数中,以确保文件数据已经读取完毕。同时,你也可以检查一下 `selectedValue` 的值是否正确获取到了选中的选项。
以下是修改后的代码示例:
```javascript
function sendMessage(data) {
const fileInput = document.getElementById("file");
const radioInput = document.getElementsByName('check')
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
const fileData = event.target.result;
const selectedValue = Array.from(radioInput).find(input => input.checked).value;
const data = {
file: fileData,
option: selectedValue
};
console.log("开始传")
console.log(selectedValue)
console.log(fileData)
socket.send(JSON.stringify(data));
};
reader.readAsArrayBuffer(file);
});
}
```
这样修改后,应该能够正确将文件数据和选项值传递到后台了。请注意确保后台的逻辑能够正确接收和处理这些数据。
阅读全文
相关推荐















