How to Upload Image From Phone to Website?

Asynchronous file uploading on the spider web and particularly the mobile spider web used to be a struggle. Three reasons come to mind:

  • AJAX'south inability to send file data meant Flash and hidden frames became the go-to solutions
  • Mobile browser support for Flash ranged from non-existent to extremely limited
  • Many mobile operating systems — including older versions of iOS, Android, Windows Phone, and BlackBerry — lacked support in their browsers for the HTML input blazon=file attribute

Thankfully, the task of asynchronous file uploading on web and mobile web has been greatly simplified recently. In this post I share some considerations and details that went into the cross-platform, photo uploading app on our mobile web app.

image00

Feature Detection vs Browser Detection

Many older mobile browsers lack back up for HTML file input. Support on electric current devices is pretty good, but there are a meaning number of old devices still in apply that cannot handle HTML file input. In guild to provide the best possible user experience, nosotros can't evidence users a characteristic their device cannot support — so we need to perform some sort of bank check to assess if the feature is supported.

One way of doing this is to check the browser's user agent and cross reference that with a list of browsers or devices that are known (either by manual testing or documentation; caniuse is a nice place to beginning) to support the feature. This is known as browser detection, and is problematic for many reasons. For one, information technology is difficult to verify all possible device/browser configurations that support the feature of interest. Additionally, it isn't future-proof: the code you write today may not piece of work tomorrow.

For these reasons, it is much better to observe if the feature of interest is available to use in the user's browser, a do known every bit feature detection. This is the goal behind the popular open up source JavaScript library Modernizr. The ideal solution would apply merely feature detection without any browser detection; however, this is not ever possible since many browsers will study faux positives on certain features.

The compromise is to use a mix of the ii methods when using only characteristic detection is non possible.

Below is a snippet of code adjusted from Modernizr that detects support for HTML file input using a mix of feature and browser detection:

Selecting a File

One time nosotros know that file input is supported, we can show the HTML input field to the user. When tapped on a mobile device, this input field volition prompt the user to either accept a new photograph with the camera, or to select an existing photo on their device. It's also possible to allow the user to select multiple photos at one time on some devices, by adding the multiple attribute to the input chemical element; nonetheless, exist aware that on iOS this will remove the option to use the camera as a source.

Note that hither nosotros utilize customer-side validation to ensure that the selected file is an image, simply it is important to validate on the server side as well. In general, validation on the client side provides amend feedback to the user, whereas server-side validation is important for security purposes.

[caption id="attachment_2452" align="aligncenter" width="450"]

A look at the file input dialogue on iOS and Android

A look at the file input dialogue on iOS and Android[/explanation]

Reading and Processing the File

The comeback of photographic camera technology in mobile devices brings with information technology an increase in the size of photos. Unfortunately, most people don't have the bandwidth (or the patience) to upload uncompressed 8+ megapixel photos on a regular basis!

So what can we practise? One solution is to compress and/or downscale photos on the customer side before we transport the photo over the network. In the past this would non have been a niggling chore, but the introduction of HTML5, the FileReader interface, and the Canvas API makes this adequately unproblematic. Let'south break this down into two parts:

  1. Using the FileReader interface to read the file
  2. Using the Canvass API to downscale and compress the image

1. Reading the File

In order to read the file, nosotros commencement need to heed for changes to the HTML input element described earlier. We can do this with a little jQuery (although the native JavaScript implementation is not much different):

In this step it tin can too be worthwhile to validate that the file is under a given size, equally loading a very big image into memory with the Canvas API is expensive, dull, and could cause the browser to crash. When the user selects an image file, the readFile function will be called with the file object. To read the file, we create a new FileReader object and define the success and failure weather condition of reading. We must read the file in one of several dissimilar formats including array buffer, binary string, data URL, and text. Y'all tin refer to the FileReader documentation for details on each of these, but for our purposes reading the file as a information URL is fine as it works quite seamlessly with the Canvass API.

2. Processing the File

Once reading the image has completed, nosotros can process it with Canvass. Outset nosotros create a new image and set its source to the data URL obtained from reading the file. When the paradigm has loaded, we summate the desired dimensions of the new prototype. Note that if the size of the new image is smaller than the original, there is no need to process the image (if scaling is our only objective).

Side by side, nosotros create a canvas element which will hold our output image. The canvas getContext method returns an object that provides methods and properties for manipulating the canvas. Nosotros utilize the drawImage method to place the source paradigm on the sheet, resulting in a downscaled version of the original image.

The canvas element provides two methods to retrieve image data: toDataURL and toBlob. Both toDataURL and toBlob have every bit arguments the output image type and the epitome quality. If the image type is specified as image/jpeg or prototype/webp, the quality argument (a number betwixt 0 and one with a default of 0.92) tin can be used to farther compress the image.

This is a fairly simple employ case of the Canvas API, though the possibilities extend far across scaling. Some examples include client side image editing, cropping, and thumbnail generation. An issue especially relevant to the mobile web is the problem of lost metadata: near browsers will ignore the EXIF metadata of photos, including the orientation tag, resulting in photos being oriented incorrectly. This is non a problem if nosotros upload the original photo, but since we are generating a new prototype with Canvas, the EXIF data of the original photograph is lost. One solution is to read the EXIF data on the client side and utilize Canvass to correctly orient the image.

Uploading the File

In recent years, the technology behind AJAX has evolved to be able to handle file uploads, so nosotros accept advantage of this to upload the file asynchronously. In that location are many benefits to asynchronous file uploading, including the ability to monitor the progress of the upload, and allowing the user to perform boosted deportment while they await for the upload to finish. Additionally, if the upload fails for whatever reason, nosotros can provide the user with a hassle-free style of retrying the upload:

[caption id="attachment_2451" align="aligncenter" width="300"]

Tap to retry a failed upload on Hootsuite's mobile web app.

Tap to retry a failed upload on Hootsuite'due south mobile web app[/explanation]

To keep things simple, we will utilise jQuery'southward ajax method to perform the request, merely if yous are familiar with the XMLHttpRequest (XHR) object this job should be no more hard.

We employ a FormData object to construct the data payload that nosotros want to send to the server. Using the FormData append method, nosotros can add key/value pairs for files, blobs, and strings to the information payload. When using jQuery and FormData, information technology is important to set up the processData and contentType backdrop to imitation. Setting processData to fake prevents jQuery from automatically converting the data into a string, while setting contentType to false will prevent jQuery from incorrectly setting the content type to its default of application/10-world wide web-form-urlencoded.

Once the file data reaches the server nosotros can handle it with the backend engineering of our option. In PHP, the file data can exist accessed in Postal service if the file data was sent as a data URL, or FILES if the file data was sent as a file or blob.

Decision

While asynchronous file uploading on the mobile spider web has long been a headache, the introduction of XMLHttpRequest Level 2 and various HTML5 APIs brand this chore much much easier. This post but covers the logic behind file processing and uploading, merely with a fleck of styling and polishing it'south quite easy to provide an crawly user experience. Check out the final production on Hootsuite'southward mobile website.

[caption id="attachment_2454" align="aligncenter" width="211"]

Photo sharing via Hootsuite's mobile web app

Photo sharing via Hootsuite's mobile web app[/caption]

Thanks

Thanks to Adam Arsenault, Lars Vedo, Jeff Stautz, Kimli Welsh, and Noel Pullen for their advice and valuable feedback.

Further Reading

  • Viljami Salminen'southward Blog — File Upload Support on Mobile
  • Mozilla Developer Network — FileReader Documentation
  • Mozilla Programmer Network — Canvass Documentation
  • Flickr — Parsing Exif client-side using JavaScript

Nigh the Author

image03

Jacob Lee is a co-op educatee on Hootsuite's mobile spider web team, studying informatics at UBC. When he's non creating web and mobile apps, he enjoys tinkering with digital media, playing hockey and tennis, and jamming on the guitar. Follow him on Twitter @jacobtwlee.

ruizstichery.blogspot.com

Source: http://code.hootsuite.com/html5/

0 Response to "How to Upload Image From Phone to Website?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel