How to Upload File and Data With Ajax

File upload through AJAX techniques tin exist daunting considering of the large amount of code, let lonely the painstaking tasks involved, such as the following:

  • Setting up an XMLHttpRequest example
  • Setting up diverse handlers on the XMLHttpRequest object
  • Setting up a back terminate to accept data from the AJAX asking
  • Validating the form
  • Setting up an efficient feedback loop for the audience

No sweat, however, thanks to Cloudinary, a cloud-based, end-to-end media-management solution that automates and streamlines the workflow for media avails, including images, videos, and audios. Specifically, Cloudinary selects, uploads, analyzes, manipulates, optimizes, and delivers those avails across devices in short lodge. Exist certain to sign up for a Gratuitous Cloudinary account and endeavor this for yourself.

This article describes how to upload AJAX files with Cloudinary with only a few lines of lawmaking and no need for any of the above tasks.

Every bit a first stride, create a gratuitous Cloudinary account, which includes a dashboard, a unique cloud proper noun for you, an API key, and an API hugger-mugger, which y'all'll need to work with Cloudinary.

Subsequently, create an upload preset, which defines the options that use to all your uploads.

Follow these iii simple steps:

Create an HTML form.

In your root directory, create an HTML grade (an index.html file) with the post-obit lawmaking, which contains the fields for file uploads:

alphabetize.html

          

<!DOCTYPE html> <html lang="en"> <caput> <meta charset="UTF-8"> <title>AJAX File Uploads With Cloudinary</title> </head> <trunk> <form id="file-grade" activity="fileUpload.php" method="mail" enctype="multipart/form-information"> Upload a File: <input type="file" id="myfile" proper noun="myfile"> <input blazon="submit" id="submit" name="submit" value="Upload File Now" > </form> <p id="condition"> </p> <script type="text/javascript" src="fileUpload.js"> </script> </body> </html>

Code linguistic communication: HTML, XML ( xml )

You lot at present take a course with the following elements:

  • An input field and a submit button.
  • An action attribute—inside the form tag—that points to the script that handles the upload.
  • A method attribute that specifies the functioning mail undertaken by this form.
  • An enctype aspect, whose value specifies the content type of the upload. Here, because the job in question is to upload files, do not specify the enctype aspect.
  • An id attribute for both input fields, which handle the form elements with JavaScript.

Add the Cloudinary JavaScript library.

JavaScript plugins on Cloudinary facilitate image uploads to its server. Include them in your index.html file, similar this:

                      <script src='https://cdn.jsdelivr.net/jquery.cloudinary/1.0.eighteen/jquery.cloudinary.js' type='text/javascript'></script>  <script src="//widget.cloudinary.com/global/all.js" type="text/javascript"></script>                  

Create a file called fileUpload.js with the following in the root directory:

          

$( office() { // Configure Cloudinary // with the credentials on // your Cloudinary dashboard $.cloudinary.config({ cloud_name: 'YOUR_CLOUD_NAME', api_key: 'YOUR_API_KEY'}); // Upload button var uploadButton = $('#submit'); // Upload-push button event uploadButton.on('click', part(e){ // Initiate upload cloudinary.openUploadWidget({ cloud_name: 'YOUR_CLOUD_NAME', upload_preset: 'YOUR_UPLOAD_PRESET', tags: ['cgal']}, function(mistake, result) { if(error) panel.log(error); // If NO error, log image data to console var id = consequence[0].public_id; console.log(processImage(id)); }); }); }) function processImage(id) { var options = { client_hints: truthful, }; return '<img src="'+ $.cloudinary.url(id, options) +'" style="width: 100%; height: auto"/>'; }

Code language: JavaScript ( javascript )

Note:

Be sure to supersede the YOUR_CLOUD_NAME, YOUR_UPLOAD_PRESET, and YOUR_API_KEY variables with their values from your Cloudinary dashboard.

To handle file uploads with AJAX and store the files on a backend server (e,g PHP Server), create an HTML form and two upload scripts: one written in JavaScript and the other in PHP.:

HTML class In your root directory, build an HTML form (an alphabetize.html file) with the following code, which contains the fields for file uploads:

          

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <championship>File Uploads With AJAX</championship> </head> <body> <form id="file-grade" action="fileUpload.php" method="mail service" enctype="multipart/form-data"> Upload a File: <input type="file" id="myfile" name="myfile"> <input blazon="submit" id="submit" name="submit" value="Upload File Now" > </form> <p id="status"> </p> <script type="text/javascript" src="fileUpload.js"> </script> </torso> </html>

Lawmaking language: HTML, XML ( xml )

Note the following:

  • The form contains an input field and a submit button.
    • The form tag has an activeness** attribute that points to the script that volition have care of the actual upload procedure. It also has a method attribute that specifies the kind of operation this form will undertake, which is mail service.
    • An enctype aspect, whose value specifies the content type of the upload. Here, because the task in question is to upload files, do not specify the enctype aspect.
    • An id attribute for both input fields, which handles the grade elements with JavaScript.

AJAX-enabled script in JavaScript

In your root directory, create a file called fileUpload.js with the post-obit lawmaking:

          

( function(){ var grade = document.getElementById('file-grade'); var fileSelect = document.getElementById('myfile'); var uploadButton = document.getElementById('submit'); var statusDiv = document.getElementById('condition'); form.onsubmit = part(event) { event.preventDefault(); statusDiv.innerHTML = 'Uploading . . . '; // Get the files from the input var files = fileSelect.files; // Create a FormData object. var formData = new FormData(); //Grab but i file since this script disallows multiple file uploads. var file = files[0]; //Check the file type. if (!file.type.lucifer('prototype.*')) { statusDiv.innerHTML = 'Y'all cannot upload this file because it'southward non an epitome.'; return; } if (file.size >= 2000000 ) { statusDiv.innerHTML = 'You cannot upload this file considering its size exceeds the maximum limit of 2 MB.'; render; } // Add the file to the AJAX request. formData.suspend('myfile', file, file.proper noun); // Set up the request. var xhr = new XMLHttpRequest(); // Open up the connection. xhr.open('POST', '/fileUpload.php', truthful); // Set up a handler for when the task for the asking is complete. xhr.onload = function () { if (xhr.condition === 200) { statusDiv.innerHTML = 'Your upload is successful..'; } else { statusDiv.innerHTML = 'An error occurred during the upload. Try once more.'; } }; // Ship the data. xhr.transport(formData); } })();

Code linguistic communication: JavaScript ( javascript )

Step by step, the process proceeds every bit follows:

Catch all the elements, i.e., the grade, the file-input, and condition div, as reflected in this code:

          

var grade = document.getElementById('file-grade'); var fileSelect = document.getElementById('myfile'); var statusDiv = document.getElementById('condition');

Code language: JavaScript ( javascript )

Call the course'due south onsubmit issue. After the user has submitted the form, adhere an event handler to the form:

          

form.onsubmit = office(event) { …. }

Lawmaking language: JavaScript ( javascript )

Get hold of the file specified by the user and, for a robust experience, keep that user informed of what's transpiring behind the scenes, like this:

          

…. statusDiv.innerHTML = 'Uploading . . . '; // Picking upwards files from the input . . . var files = fileSelect.files; // Uploading only one file; multiple uploads are not allowed. var file = files[0]; ...

Code language: JavaScript ( javascript )

Create a form object, validate the size and type of the file to exist uploaded, and add together the file to form, similar this:

          

// Create a FormData object. var formData = new FormData(); //Cheque the file type. if (!file.type.match('prototype.*')) { statusDiv.innerHTML = ''You lot cannot upload this file considering it's non an image.'; render; } if (file.size >= 2000000 ) { statusDiv.innerHTML = 'You cannot upload this file because its size exceeds the maximum limit of two MB.'; render; } // Add the file to the asking. formData.suspend('myfile', file, file.name);

Code linguistic communication: PHP ( php )

Fix upwardly an AJAX request, open a connectedness, and listen for the onload effect of the xhr object.

          

// Set up an AJAX asking. var xhr = new XMLHttpRequest(); // Open up the connexion. xhr.open up('Mail', '/fileUpload.php', true); // Set upwardly a handler for when the task for the request is complete. xhr.onload = role () { if (xhr.status === 200) { statusDiv.innerHTML = Your upload is successful.'; } else { statusDiv.innerHTML = 'An error occurred while uploading the file...Endeavor once again'; } }; // Ship the Data. xhr.send(formData);

Code language: PHP ( php )

Here, you lot make a post request to fileUpload.php. And yes, you must however process the file on the back terminate, to which the AJAX request submits the file for processing.

Before leveraging the preceding code for production, you must make provisions for several edge cases, for case, perform checks to ensure that only safe files are posted to your dorsum cease.

PHP script

Below is the script written in PHP.

          

<?php $currentDir = getcwd(); $uploadDirectory = "/uploads/"; $errors = []; // Store all foreseen and unforeseen errors hither. $fileExtensions = ['jpeg','jpg','png']; // Get all the file extensions. $fileName = $_FILES['myfile']['proper noun']; $fileSize = $_FILES['myfile']['size']; $fileTmpName = $_FILES['myfile']['tmp_name']; $fileType = $_FILES['myfile']['type']; $fileExtension = strtolower(end(explode('.',$fileName))); $uploadPath = $currentDir . $uploadDirectory . basename($fileName); repeat $uploadPath; if (isset($fileName)) { if (! in_array($fileExtension,$fileExtensions)) { $errors[] = "This procedure does not back up this file type. Upload a JPEG or PNG file simply."; } if ($fileSize > 2000000) { $errors[] = "Y'all cannot upload this file because its size exceeds the maximum limit of two MB."; } if (empty($errors)) { $didUpload = move_uploaded_file($fileTmpName, $uploadPath); if ($didUpload) { repeat "The file " . basename($fileName) . " has been uploaded."; } else { echo "An error occurred. Try again or contact your organization administrator."; } } else { foreach ($errors as $fault) { echo $error . "These are the errors" . "\northward"; } } } ?>

Lawmaking linguistic communication: HTML, XML ( xml )

Note:

Ensure you are running a PHP server, such as this i:

PHP server

Now when you run that PHP app, it looks like this: run application

In addition, note the following:

  • The PHP script works for image files only.
  • The file-size limit is a file two MB.

Upload images to a dedicated file server in addition to the server in which your web app resides. Cheque out this source lawmaking for a related tutorial.

Uploading AJAX files with Cloudinary is a breeze. Even though mastering AJAX technologies could be challenging, y'all tin can accept advantage of them readily with the Cloudinary library for your app. Give it a try: signing upward for Cloudinary is gratis.


  • Automating File Upload and Sharing
  • Uploading PHP Files and Rich Media the Easy Way
  • AJAX File Upload – Quick Tutorial & Time Saving Tips
  • Impressed past WhatsApp technology? Clone WhatsApp Technology to Build a File Upload Android App
  • Direct Image Uploads From the Browser to the Deject With jQuery
  • File Upload With Angular to Cloudinary
  • Uploading Vue Files and Rich Media in Two Easy Steps
  • Node.js File Upload To a Local Server Or to the Cloud
  • Laravel File Upload to a Local Server Or to the Cloud
  • JavaScript File Upload in Two Elementary Step

fieldssuriagiven.blogspot.com

Source: https://cloudinary.com/blog/file_upload_with_ajax

0 Response to "How to Upload File and Data With Ajax"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel