javascript upload file
javascriptTo upload a file using JavaScript, you can use the HTML5 File API. Here’s an example code snippet:
HTML code:
<input type="file" id="myFileInput">
<button onclick="uploadFile()">Upload File</button>
JavaScript code:
function uploadFile() {
const input = document.getElementById('myFileInput');
const file = input.files[0];
const formData = new FormData();
formData.append('file', file);
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => {
console.log('File uploaded successfully');
})
.catch(error => {
console.error('Error uploading file:', error);
});
}
In the HTML code, we create an input element of type “file” and an HTML button that calls the uploadFile() function when clicked.
In the JavaScript code, we first get the selected file using the getElementById() method and accessing the files property of the input element.
Then, we create a new FormData object and append the file to it using the append() method.
Finally, we use the fetch() method to send a POST request to the server with the file data in the body of the request. In this example, we assume that the server will handle the file upload at the /upload endpoint. The response from the server is logged to the console.
Other Article on Tag javascript
- - Adding and removing content in jQuery
- - Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
- - Can I change the Dojo namespace to something other than dojo
- - Can I prevent user pasting Javascript into Design Mode IFrame
- - dynamically create html element in javascript
- - Find XY of an HTML element with JavaScript
- - How can I upload files asynchronously with jQuery
- - How can you display Typing Speed using Javascript or the jQuery library
- - How do you capture mouse events in firefox
- - How to auto-size an iFrame