How to upload a file in JavaScript
Uploading files in JavaScript enables users to submit documents, images, and other files to your server without page refreshes. As the creator of CoreUI with over 25 years of JavaScript development experience, I’ve implemented file uploads in countless production applications for user profiles and document management. The most reliable approach uses FormData with the fetch API to handle file uploads with proper content types. This method provides secure file transfer while maintaining full control over the upload process and error handling.
Use FormData with fetch API to upload files securely to your server.
function uploadFile(file) {
const formData = new FormData()
formData.append('file', file)
return fetch('/api/upload', {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error('Upload failed')
}
return response.json()
})
}
// Usage with file input
const fileInput = document.querySelector('input[type="file"]')
fileInput.addEventListener('change', async (event) => {
const file = event.target.files[0]
if (file) {
try {
const result = await uploadFile(file)
console.log('Upload successful:', result)
} catch (error) {
console.error('Upload error:', error)
}
}
})
This code creates a FormData object and appends the selected file to it, then sends it via fetch to your upload endpoint. The FormData automatically sets the correct content type for multipart file uploads. The function returns a promise that resolves with the server response or rejects with an error for failed uploads.
Best Practice Note:
This is the upload mechanism we use in CoreUI dashboard components for file management features. Always validate file types and sizes both client-side and server-side to prevent security issues and ensure proper file handling.



