jquery image upload in javascript

Here's a basic example of how to upload an image file using jQuery:

HTML code:

index.tsx
<form>
  <input type="file" id="fileUpload">
  <input type="button" value="Upload" onclick="uploadFile()">
</form>
115 chars
5 lines

JavaScript code:

index.tsx
function uploadFile() {
  // Get the file upload control and the file
  var file = $("#fileUpload").get(0).files[0];

  // Create a new FormData object
  var formData = new FormData();

  // Append the file to the FormData object
  formData.append("file", file);

  // Use jQuery AJAX to upload the file
  $.ajax({
    url: "/upload",
    type: "POST",
    data: formData,
    processData: false,
    contentType: false,
    success: function(response) {
      // Handle successful upload
    },
    error: function(xhr, status, error) {
      // Handle upload error
    }
  });
}
581 chars
26 lines

This code creates an HTML form with an file upload control and a "Upload" button. When the user clicks the "Upload" button, the uploadFile function is called. This function gets the file from the file upload control, creates a FormData object, appends the file to the FormData object, and then uses jQuery AJAX to upload the file to the server.

Note that this is a very basic example and you will likely need to add additional logic to handle errors, display progress, etc.

related categories

gistlibby LogSnag