I'm trying to make a simple multiple file upload using solid.js:
import { createSignal } from 'solid-js';
function App() {
const [files, setFiles] = createSignal([]);
function handleFileChange(event) {
const selectedFiles = Array.from(event.target.files);
setFiles(() => selectedFiles);
selectedFiles.forEach(file => {
console.log('Selected file:', file.name);
console.log('File size:', file.size);
});
}
async function uploadFiles() {
const formData = new FormData();
for (const file of files()) {
formData.append('file', file);
}
// Send the file to the server using fetch or your preferred method
try {
const response = await fetch('http://127.0.0.1:8090/upload', {
method: 'POST',
body: formData,
});
console.log('File uploaded successfully');
} catch (error) {
console.error('Error uploading file:', error);
}
}
return (
<div class={styles.App}>
<div class={styles.item}>
<input type="file" multiple onChange={handleFileChange} />
<button onclick={uploadFiles}>Upload</button>
</div>
</div>
);
}
export default App;
In the console I see the file names and their sizes:
Selected file: Track01.mp3
App.jsx:16 File size: 1650939
App.jsx:15 Selected file: Track02.mp3
App.jsx:16 File size: 1919269
App.jsx:15 Selected file: Track03.mp3
App.jsx:16 File size: 1338305
App.jsx:37 File uploaded successfully
But in the backend empty files is received:
files: []
And no file is saved in the destination path.
Then I read that createSignal does not allow arrays so I used const [files, setFiles] = createStore([]);
and for (const file of files)
respectively, buts still got the same result.
I've also tried uploadFiles
snycronously, but without luck.
I'm new to solid.js. Just wondering why this happens and how can I fix it?