upload an image in javascript

To upload an image in JavaScript, you can use the FileReader API to read the file data and create a FormData object to send the data via an Ajax request. Here's an example code snippet:

HTML:

<input type="file" id="image-file">
<button type="button" onclick="uploadImage()">Upload Image</button>
104 chars
3 lines

JavaScript:

index.tsx
function uploadImage() {
  const input = document.getElementById('image-file');
  if (input.files && input.files[0]) {
    const reader = new FileReader();
    reader.onload = function(e) {
      const formData = new FormData();
      formData.append('image', e.target.result);
      // send formData via Ajax request
      // e.g. using fetch or XMLHttpRequest
    }
    reader.readAsDataURL(input.files[0]);
  }
}
416 chars
14 lines

In this example, we first get the input element for file selection and check if it contains any files. Then, we create a FileReader object and set its onload function to append the file data to a FormData object. Finally, we send the FormData object via an Ajax request, for example using fetch or XMLHttpRequest.

gistlibby LogSnag