www.webdeveloper.com
Results 1 to 15 of 101

Thread: Resize, preview and upload an image with AJAX - Complete example

Threaded View

  1. #1
    Join Date
    May 2009
    Location
    Madrid, Spain
    Posts
    40

    Resize, preview and upload an image with AJAX - Complete example

    Hello,

    I wanted to do an Ajax script to resize and preview and image in an html form. Well, I didn't find how to do with Ajax, so I had to use php.

    The issue is that JavaScript cannot manage a file field to get the selected file and send it via Ajax. The only way to send a file is submitting a form. To not send all data of the form, the file field must be a separate form from the rest of the data. So it can be automatically sent to a php script, which resizes the image, uploads it and then can display it in a iframe without reloading the page.

    Then you have the resized image previewed in the form without submitting all data. And then you can send all data with Ajax, including the path of the previously uploaded image, which is stored as a variable in the iframe.

    I use one html file and two php scripts, which in total are less than 20 KB.

    What do you think about this approach?

    Kind regards

    HTML Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <!--
    Author: Alberto Moyano Sánchez
    Date: 2009-05-24
    Description: [...]
    Notes and improvements: [...]
    -->
    <html>
      <head>
        <title>
          Upload and preview an image with Ajax
        </title>    
        <script language="JavaScript" type="text/javascript">
          
          var loadingHtml = "Loading..."; // this could be an animated image
          var imageLoadingHtml = "Image loading...";
        	var http = getXMLHTTPRequest();
          //----------------------------------------------------------------
        	function uploadImage() {
            var uploadedImageFrame = window.uploadedImage;
        	  uploadedImageFrame.document.body.innerHTML = loadingHtml;
        	  // VALIDATE FILE
            var imagePath = uploadedImageFrame.imagePath;
            if(imagePath == null){
              imageForm.oldImageToDelete.value = "";
            }
            else {
              imageForm.oldImageToDelete.value = imagePath;
            }
            imageForm.submit();
          }
          //----------------------------------------------------------------
          function showImageUploadStatus() {
            var uploadedImageFrame = window.uploadedImage;
            if(uploadedImageFrame.document.body.innerHTML == loadingHtml){
              divResult.innerHTML = imageLoadingHtml;
            }
            else {
              var imagePath = uploadedImageFrame.imagePath;
              if(imagePath == null){
                divResult.innerHTML = "No uploaded image in this form.";
              }
              else {
                divResult.innerHTML = "Loaded image: " + imagePath;
              }
            }
          }
          //----------------------------------------------------------------
          function getXMLHTTPRequest() {
          	try {
            	xmlHttpRequest = new XMLHttpRequest();
          	}
          	catch(error1) {
            	try {
              	xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
              }
              catch(error2) {
          	    try {
          		    xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
          	    }
          	    catch(error3) {
          		    xmlHttpRequest = false;
          	    }
              }
            }
            return xmlHttpRequest;
          }
          //----------------------------------------------------------------
          function sendData() {
          	var url = "submitForm.php";
            var parameters = "imageDescription=" + dataForm.imageDescription.value;
            var imagePath = window.uploadedImage.imagePath;
            if(imagePath != null){
              parameters += "&uploadedImagePath=" + imagePath;
            }
            
          	http.open("POST", url, true);
        
            http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            http.setRequestHeader("Content-length", parameters.length);
            http.setRequestHeader("Connection", "close");
        
          	http.onreadystatechange = useHttpResponse;
          	http.send(parameters);
          }
          //----------------------------------------------------------------
          function submitFormIfNotImageLoading(maxLoadingTime, checkingIntervalTime) {
            if(window.uploadedImage.document.body.innerHTML == loadingHtml) {
              if(maxLoadingTime <= 0) {
                divResult.innerHTML = "The image loading has timed up. "
                                    + "Please, try again when the image is loaded.";
              }
              else {
                divResult.innerHTML = imageLoadingHtml;
                maxLoadingTime = maxLoadingTime - checkingIntervalTime;
                var recursiveCall = "submitFormIfNotImageLoading(" 
                                  + maxLoadingTime + ", " + checkingIntervalTime + ")";
                setTimeout(recursiveCall, checkingIntervalTime);
              }
            }
            else {
              sendData();
            }
          }
        	//----------------------------------------------------------------
          function submitForm() {
            var maxLoadingTime = 3000; // milliseconds
            var checkingIntervalTime = 500; // milliseconds
            submitFormIfNotImageLoading(maxLoadingTime, checkingIntervalTime);
          }
          //----------------------------------------------------------------
          function useHttpResponse() {
          	if (http.readyState == 4) {
            	if (http.status == 200) {
              	divResult.innerHTML = http.responseText;
              	dataForm.reset();
              	imageForm.reset();
              	window.uploadedImage.document.body.innerHTML = "";
              	window.uploadedImage.imagePath = null;
            	}
          	}
          }
    
        </script>
      </head>
      <body>
        <h3>
          Form with preview of resized image with Ajax
        </h3>
        <form id="dataForm" name="dataForm">
          Image description: 
          <input name="imageDescription" id="imageDescription" type="text" 
                size="30"/>
        </form>
        
        <form id="imageForm" name="imageForm" enctype="multipart/form-data"
              action="uploadImage.php" method="POST" target="uploadedImage">
          <!-- Next field limits the maximum size of the selected file to 2MB.
               If exceded the size, an error will be sent with the file. -->
          <input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
          Image: 
          <input name="imageToUpload" id="imageToUpload" type="file"
                onchange="uploadImage();" size="30"/>
          <br />
          Old uploaded image to delete (this field should be hidden):
          <br />
          <input name="oldImageToDelete" id="oldImageToDelete" type="text"
                size="50" />
        </form>
        
        <iframe id="uploadedImage" name="uploadedImage" src="" 
              style="width:200px; height:200px;"
              frameborder="0" marginheight="0" marginwidth="0"></iframe>
        
        <br /><br />
        
        <form>
        <input type="button" onclick="submitForm();" value="Submit" />
        </form>
    
        <br />
        
        <form>
        <input type="button" onclick="showImageUploadStatus();" value="Show image upload status" />
        </form>
        
        <div id="divResult"></div>
    
      </body>
    </html>
    Attached Files Attached Files

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles