Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to render HTML to an image ?
Next article icon

How to Send an Image using Ajax ?

Last Updated : 06 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Ajax stands for Asynchronous Javascript and XML and is used to make indirect requests to other origins. It can help you to perform a change to the web page dynamically.

We can make an AJAX request with a special object called XMLHttpRequest which provides us with different methods to create an HTTP requests.

Syntax:

xhr = new XMLHttpRequest();
xhr.onload = ()=>{...};
xhr.open(<method>,<url>);
xhr.send();

Methods Used:

  1. open: This accepts 3 parameters:
    • method: the HTTP method
    •  url: the resource path
    • async / sync      
  2. send: Sends the final request
  3. onload: To listen for the response

In this article, we will learn to upload an image using AJAX.

Approach:

To send an image we need to make a post request to the server and upload the image firstly by converting it into DATAURL format.

Steps:

  • Use a file input button to select an image
  • Add an oninput event listener which gets the uploaded file with e.target.files property
  • Using FileReader.readAsDataURL method converts the acquired file into dataurl.
  • Getting the input creates a new instance of XMLHttpRequest 
  • Prepare the POST request and send the  data in string format
  • On the server side, we are using express to listen for POST requests at localhost:3000

Example 1: Below is the implementation of the above steps:

  • Client: This is the client-side code that uploads the image to the server.
HTML
<html>   <body>       <input type="file"/>     <script type="text/javascript">         let result;         let input = document.getElementsByTagName('input')[0];         input.oninput=(e)=>{             console.log(e);             let file = e.target.files[0];              const reader = new FileReader();               reader.onload = (evt) => {                     console.log(evt.target.result);                     result = evt.target.result;                           const xhr = new XMLHttpRequest();       const url = 'http://localhost:3000/events';        xhr.open('POST', url);       xhr.send(result);               };               reader.readAsDataURL(file);         }     </script>   </body> </html> 
  • Server: Accepting the Image with EXPRESS post listener
JavaScript
'use strict';  const express = require('express'); run().catch(err => console.log(err)); async function run() {     const app = express();      app.post('/events', (req, res) => {         res.set({             'Cache-Control': 'no-cache',             'Access-Control-Allow-Origin': '*'         });         req.on("data", (data) => {             console.log(data.toString());         })         res.send();     }) }   

Output:

OUTPUT

In the above GIF image, we find that the image is getting transferred in DATAURL format. The tabs on the left represent the client and the large black tab on the right represents the server.

We can select the image with the file input button and immediately the transfer takes place.

Example 2:

In this example, we will send an image and display the image which is reverted back from the server.

Project Structure:

ajax-folder
Folder structure

Steps to Send an Image using Ajax using Express :

Step 1: Create a New Directory

First, create a new directory for your project and navigate into it.

mkdir Your_folder_name
cd Your_folder_name

Step 2: Initialize a New Node.js Project

After that, you have to Initialize a new node project using npm.

npm init -y

Step 3: Install the required packages

Then install the required package using npm.

npm install express ejs multer

Updated dependencies:

"dependencies": {
"ejs": "^3.1.10",
"express": "^4.19.2",
"multer": "^1.4.5-lts.1"
}
}

Example: Below is the code example of how to How to Send an Image using Ajax using Express

HTML
<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Upload Image with Ajax</title>     <link rel="stylesheet" href="/style.css"> </head> <body>     <div class="container">         <h2>Upload Image</h2>         <form id="uploadForm" enctype="multipart/form-data">             <input type="file" id="image" name="image" accept="image/*" required>             <button type="submit">Upload</button>         </form>         <div id="response"></div>     </div>     <script src="/script.js"></script> </body> </html> 
CSS
/* Write CSS Here */ body {     font-family: Arial, sans-serif;     display: flex;     justify-content: center;     align-items: center;     height: 100vh;     margin: 0;     background-color: #f4f4f4; }  .container {     background: white;     padding: 20px;     border-radius: 10px;     box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);     text-align: center; }  h2 {     margin-bottom: 20px;     color: #14e777; }  input[type="file"] {     display: block;     margin: 0 auto 20px; }  button {     padding: 10px 20px;     background-color: #007bff;     color: white;     border: none;     border-radius: 5px;     cursor: pointer; }  button:hover {     background-color: #0056b3; }  img {     margin-top: 20px;     max-width: 100%;     height: auto;     border: 1px solid #ddd;     border-radius: 10px;     padding: 5px; } 
JavaScript
// server.js code... const express = require('express'); const multer = require('multer'); const path = require('path');  const app = express(); const port = 3000;  // Set up storage engine const storage = multer.diskStorage({     destination: './uploads/',     filename: (req, file, cb) => {         cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));     } });  // Initialize upload const upload = multer({     storage: storage,     limits: { fileSize: 1000000 }, // Limit file size to 1MB     fileFilter: (req, file, cb) => {         checkFileType(file, cb);     } }).single('image');  // Check file type function checkFileType(file, cb) {     const filetypes = /jpeg|jpg|png|gif/;     const extname = filetypes.test(path.extname(file.originalname).toLowerCase());     const mimetype = filetypes.test(file.mimetype);      if (mimetype && extname) {         return cb(null, true);     } else {         cb('Error: Images Only!');     } }  // Set view engine app.set('view engine', 'ejs');  // Public folder app.use(express.static('./public')); app.use('/uploads', express.static(path.join(__dirname, 'uploads')));  // Routes app.get('/', (req, res) => res.render('index'));  app.post('/upload', (req, res) => {     upload(req, res, (err) => {         if (err) {             res.status(400).send({ msg: err });         } else {             if (req.file == undefined) {                 res.status(400).send({ msg: 'No file selected!' });             } else {                 res.status(200).send({                     msg: 'File uploaded successfully!',                     file: `uploads/${req.file.filename}`                 });             }         }     }); });  app.listen(port, () => console.log(`Server started on http://localhost:${port}`)); 
JavaScript
//script.js code   document.getElementById('uploadForm').addEventListener('submit', function(event) {     event.preventDefault();      let formData = new FormData();     let image = document.getElementById('image').files[0];     formData.append('image', image);      let xhr = new XMLHttpRequest();     xhr.open('POST', '/upload', true);      xhr.onload = function() {         let response = document.getElementById('response');         if (xhr.status === 200) {             let data = JSON.parse(xhr.responseText);             response.innerHTML = `<p>${data.msg}</p><img src="${data.file}" alt="Uploaded Image">`;         } else {             let data = JSON.parse(xhr.responseText);             response.innerHTML = `<p>${data.msg}</p>`;         }     };      xhr.send(formData); }); 

Output:

compressed_ajax
Output

Next Article
How to render HTML to an image ?
author
nikhilkalburgi
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • How to use simple API using AJAX ?
    AJAX (Asynchronous JavaScript and XML) is a set of tools used to make calls to the server to fetch some data. In this article, we will see how to implement a simple API call using AJAX. Prerequisites: Basic knowledge of AJAX and its function. You can learn all the basics from here. What are basic bu
    3 min read
  • How to Change Image Source URL using AngularJS ?
    Here the task is to change the source URL of the image with the help of AngularJS. Approach: The approach is to change the URL of the image when the user click on button. When a user clicks on a button then a method is called along with the new URL, that method replaces the new URL with the old one
    2 min read
  • How to use JSON in Ajax jQuery ?
    Using JSON in AJAX requests with jQuery is a fundamental aspect of web development. JSON or JavaScript Object Notation, offers a lightweight and structured format for data exchange between a server and a web application. jQuery simplifies this process further through its AJAX functionalities. We wil
    3 min read
  • How to Drag and Drop Images using HTML5 ?
    In this article, we will see how to create a drag and drop functionality using HTML5. Approach: The following approach will be implemented to Drag and Drop Images using HTML5. We have given a rectangle area and an image, the task is to drag the image and drop it into the rectangle.We have to enable
    2 min read
  • How to render HTML to an image ?
    Converting HTML code into an image can be achieved through various methods, such as using the html2canvas JavaScript library or leveraging CSS. This capability is particularly useful for users who wish to share a visual representation of their code without sharing the actual code. This guide will de
    3 min read
  • How to submit a form using ajax in jQuery ?
    Submitting a form using AJAX in jQuery allows sending form data to a server asynchronously without reloading the page. This method improves user experience by sending the data in the background and receiving a response without interrupting the user's interaction with the webpage. Syntax:$.ajax({type
    2 min read
  • How to Create an Image Element using JavaScript?
    We will dynamically create an <img> element in HTML using JavaScript. When a button is clicked, we'll generate the <img> element and append it to the document. Using createElement() methodCreate an empty img element using document.createElement() method.Then set its attributes like (src,
    1 min read
  • How to change the background image using jQuery ?
    To change the background image using jQuery, you can use the jQuery CSS() method. For this, the whole property value is specified using the url() functional notation. Approach: Suppose we have an image URL stored in a variable and then use css() method to change the value of background image. Below
    1 min read
  • How to make a JSON call using jQuery ?
    Use the getJSON() function in jQuery to load JSON data. The getJSON() function uses a GET HTTP request to retrieve JSON-encoded data from the server. In this article, we will learn about the jQuery getJSON() function and its implementation through examples. Syntax: $(selector).getJSON(url, data, suc
    3 min read
  • How to display Image in Postman using Express ?
    Postman is a powerful tool for testing APIs, but when it comes to displaying images, it can be a little bit tricky. This article, the process of setting up an Express server to serve images and accessing them using Postman. Prerequisites:PostmanExpress JSSteps to display Image in Postman:Step 1: Ima
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences