Take a Photo and Upload it on Mobile Phones with HTML5

In my daily life, I enjoy taking photos with my smartphone and uploading them to various websites. So I started thinking, “Is it possible to implement these functions in a web browser?” Although Dynamsoft ImageCapture Suite allows us to capture images from a webcam, it is designed for a desktop App development on windows and Mac, not for mobile platforms. Fortunately, the new HTML5 SDK is capable of uploading local images or captured images to web servers. Everything becomes easier if we have a mobile web browser, like Chrome, which is fully compatible with HTML5.

Dynamsoft Barcode Reader SDK
Ads Powered by Dynamsoft

Take Photos in Browsers of Android and iOS

Using HTML5 to invoke the camera is very simple.

For more information, you can reference HTML Media Capture. Due to the platform-dependency, you need to read Mobile HTML5 and search HTML Media Capture for relevant information. Referring to the article Html5 File Upload with Progress, I have made some improvements. The source code has been tested on Android 4.1 and iOS 7.0.6. You can see the following figures.

Android:

android

iOS: 

image capture image upload

For ASP.Net

Client:

<!DOCTYPE html>

<html>

<head>

    <title>Take or select photo(s) and upload</title>

    <script type="text/javascript">

      function fileSelected() {

        var count = document.getElementById('fileToUpload').files.length;

              document.getElementById('details').innerHTML = "";

              for (var index = 0; index < count; index ++)

              {

                     var file = document.getElementById('fileToUpload').files[index];

                     var fileSize = 0;

                     if (file.size > 1024 * 1024)

                            fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';

                     else

                            fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';

                     document.getElementById('details').innerHTML += 'Name: ' + file.name + '<br>Size: ' + fileSize + '<br>Type: ' + file.type;

                     document.getElementById('details').innerHTML += '<p>';

              }

      }

      function uploadFile() {

        var fd = new FormData();

              var count = document.getElementById('fileToUpload').files.length;

              for (var index = 0; index < count; index ++)

              {

                     var file = document.getElementById('fileToUpload').files[index];

                     fd.append(file.name, file);

              }

        var xhr = new XMLHttpRequest();

        xhr.upload.addEventListener("progress", uploadProgress, false);

        xhr.addEventListener("load", uploadComplete, false);

        xhr.addEventListener("error", uploadFailed, false);

        xhr.addEventListener("abort", uploadCanceled, false);

        xhr.open("POST", "savetofile.aspx");

        xhr.send(fd);

      }

      function uploadProgress(evt) {

        if (evt.lengthComputable) {

          var percentComplete = Math.round(evt.loaded * 100 / evt.total);

          document.getElementById('progress').innerHTML = percentComplete.toString() + '%';

        }

        else {

          document.getElementById('progress').innerHTML = 'unable to compute';

        }

      }

      function uploadComplete(evt) {

        /* This event is raised when the server send back a response */

        alert(evt.target.responseText);

      }

      function uploadFailed(evt) {

        alert("There was an error attempting to upload the file.");

      }

      function uploadCanceled(evt) {

        alert("The upload has been canceled by the user or the browser dropped the connection.");

      }

    </script>

</head>

<body>

  <form id="form1" enctype="multipart/form-data" method="post" action="Upload.aspx">

    <div>

      <label for="fileToUpload">Take or select photo(s)</label><br />

      <input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();" accept="image/*" capture="camera" />

    </div>

    <div id="details"></div>

    <div>

      <input type="button" onclick="uploadFile()" value="Upload" />

    </div>

    <div id="progress"></div>

  </form>

</body>

</html>

Server savetofile.aspx:

<%@ Page Language="C#" %>

<%

       HttpFileCollection files = HttpContext.Current.Request.Files;

       for (int index = 0; index < files.Count; index ++)

       {

              HttpPostedFile uploadfile = files[index];

                             // You must create “upload” sub folder under the wwwroot.

              uploadfile.SaveAs(Server.MapPath(".") + "\\upload\\" + uploadfile.FileName);

       }

             HttpContext.Current.Response.Write("Upload successfully!");

%>

For PHP

Modify the client:

1.    Change

fd.append(file.name, file);

To

fd.append('myFile', file);

2.    Change

xhr.open("POST", "savetofile.aspx");

To

xhr.open("POST", "savetofile.php");

Create savetofile.php:

<?php
if (isset($_FILES['myFile'])) {
    // Example:
    move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
    echo 'successful';
}
?>

Source Code

https://github.com/DynamsoftRD/HTML5-Photo-Upload

 

40 thoughts on “Take a Photo and Upload it on Mobile Phones with HTML5

  1. savetofile.aspx saves to ./upload/*.jpg
    savetofile.php saves to ./uploads/*.jpg

    You need to create this subdirectory manually before running the code.

  2. First of all thanks for great tutorials.

    I am using your tutorial in one of my application and its really very nice.

    but I have one question, Before saving image to server, how can we allow user if they want to rename image name in mobile and after that save into server ?
    Please need your helps.

  3. Your company needs to thank you for not posting here the link to your project so that hackers could attack on it

  4. How can I also specify the filename to save the image as from the form? I need to be able to pass the new filename to another php page where it will save the url of the uploaded image into a database.
    Ideally I would like to timestamp the filename so as to avoid file overwrites with same name.

  5. I have uploaded this to my web hosting now and it looks like it works but i cant see the uploaded file in the folder structure anywhere?? Do i need to create a place for it to upload to? I get the success message and it moves to 100% but no images to be seen…

  6. working great in browser…but i want to load it in my app ..when app load html page i click on choose file ..nothing happen ….i m using marshmallow

  7. Hi Thank Its Real Work 100%, Suppliant> Make New Three Folder In Root> uploads, myFile, tmp_name,Now Uploade And Look File Uploads Folder Thank

  8. Is it possible to resize or limit the max resolution on client-side, before uploading?

    I found this on the internet, that i can be done with javascript:

    if (window.File && window.FileReader && window.FileList && window.Blob) {

    document.getElementById(‘filesToUpload’).onchange = function(){

    var files = document.getElementById(‘filesToUpload’).files;

    for(var i = 0; i tempH) {

    if (tempW > MAX_WIDTH) {

    tempH *= MAX_WIDTH / tempW;

    tempW = MAX_WIDTH;

    }

    } else {

    if (tempH > MAX_HEIGHT) {

    tempW *= MAX_HEIGHT / tempH;

    tempH = MAX_HEIGHT;

    }

    }

    var canvas = document.createElement(‘canvas’);

    canvas.width = tempW;

    canvas.height = tempH;

    var ctx = canvas.getContext(“2d”);

    ctx.drawImage(this, 0, 0, tempW, tempH);

    var dataURL = canvas.toDataURL(“image/jpeg”);

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function(ev){

    document.getElementById(‘filesInfo’).innerHTML = ‘Done!’;

    };

    xhr.open(‘POST’, ‘uploadResized.php’, true);

    xhr.setRequestHeader(“Content-type”,”application/x-www-form-urlencoded”);

    var data = ‘image=’ + dataURL;

    xhr.send(data);

    }

    }

    reader.readAsDataURL(file);

    }

    Any ideas how to make this work with the script you guys gave in this article?

    Link: http://www.codeforest.net/html5-image-upload-resize-and-crop

  9. Hi, can any help me save the image in a folder created dynamically, folder name need to be fetched from url of the html page

  10. Great code, works a treat.
    Can you post some sample code showing how to obtain the filename of the image in the uploadComplete function so that I can display it as a thumbnail on the page?
    Thanks in advance

  11. I cant believe, this, after like 6 days of search and studing javascript into learning how to put a video feed back of cell camera to the webbrowser… and then find this site, dude i cant thank you enough.

    I literally plug all of the code in, put the php in wwroot, and IT WORKED!!!!!

    no trouble shoot no error, NOTHING, just put it in and press go, very easy code to understand too.

    Thank you very much, the company i work for thanks you.

  12. Thanks for this useful demo. I can already think of an application of it. I’d have to add something to the php as the upload will grab the same name from an iPhone (image.jpg) so uploads from different users would overwrite previous uploads. Thanks again.

  13. Awesome code for take a photo feature. but is there any way to upload capture photos to landscape its uploaded portrait yet. Many thanks in advance

  14. Good day!
    I am trying to use this example and got everything working fine up to a point. Using Intel XDK and Windows Server 2008 R2 with the .aspx code I got it working perfectly in the Chrome window of the Intel XDK. However, Using the emulator or deploying to an actual Android device, does not work. Exactly the same code that works in Chrome does nothing on the device or emulator. No error message or anything. Any ideas or more info I can provide?
    Thanks in advance

  15. My files are not posting to the directory,…I am getting a 500 Internal server error on line 69. Any ideas? Thanks

  16. Hello, i have the problem
    In iphone, it can choose image file when click the choose file button
    but when i try to using android, when i click the choose file button, it go to camera, not go to choose image page…..

  17. This is great tutorial but I tried saving it to database as well and it worked too. But I would like to get some html input text also such as How can i acheive that many thanks in advance

  18. Please check the post update – For PHP. The PHP code is very simple: move_uploaded_file($_FILES[‘myFile’][‘tmp_name’], “uploads/” . $_FILES[‘myFile’][‘name’]);

  19. The HTML part works very well but I’m running a Ubuntu 12.04LTS and installing ASP is not an option.

    Is there an alternative to using aspx?

  20. This seems great. I’ve been looking to play with the for some time. Does anyone know what might need to be done for savetofile.aspx to be in PHP?

Comments are closed.