Mobile picture operation (i)--upload

Source: Internet
Author: User

Uploading we are generally using the "input[type=file" control. When you use this control, you authorize the Web page and the server to access the corresponding files, you can get the file object.

Friendship hint in, in the Android phone WebView, is not support upload files, online said is to modify the Android code, but I have not tried, our side is to use the interface provided by the client to achieve the upload.

The following sample code can be found here .

First, the Accept attribute

This property indicates the server-side acceptable file types, you can limit your phone selection of related files, if the limit of multiple, can be separated by commas, the following code indicates that only the image and audio-related files are selected:

<accept= "image/*,audio/*"  type= "file"/>

On the mobile side, the click will let you choose a photo or photo album, or pretty Tall on the. is in the UC browser:

Second, the Change event

The general selection file will use the "Change" event, the following code is bound to the Change event, pop-up file size:

var upload = document.getElementById (' upload '); Upload.addeventlistener (function() {   var file = Upload.files[0];   false);

1) Some mobile browsers when clicked, will pop up the keyboard selection, I use onfocus= "This.blur ()", to force the loss of focus.

<type= "file"  ID= "Upload"  onfocus= "This.blur ()"  />

2) When selected once, select the same file again, "change" event will not be triggered, because the value has not changed, see a method on the Internet, I have not been used in the actual project, compatibility needs to be verified.

Use the Node. cloneNode"Copy the upload element and then use" Node. replacechild"Replace node.

Note here that cloning an element node copies all of its attributes and property values, but does not copy events that are dynamically bound with JavaScript using the AddEventListener () method or Node.onclick = fn.

function () {  var// each time you want to dynamically get  var file = Upload.files[0];  Console.log (file.size);   // resolve upload of same file does not trigger  onchange event  var clone = Upload.clonenode (true);   // clones do not replicate dynamic bound events  Clone.value = ";   false);

Third, File object

The files selected by the user are stored on a FileList object, each of which corresponds to a file object

The file object is responsible for processing binary data that exists as files, that is, manipulating local files.

The file object is a special type of blob"to be mentioned", that is, large chunks of binary data, and attributes such as the size and type of the file object inherit from the Blob.

1) The file object can be obtained in 3 ways:

1. Members of the FileList object returned after selecting a file on the <input> element

2. Drag-and-drop operation "Drag or drop" the members of the files property in the generated datatransfer object

3. Return results after executing the Mozgetasfile () method on htmlcanvaselement

document.getElementById (' upload '). Files[0]// Select the first file object

2) The file object has 9 properties, here are only 3:

1. name: The file name of the file referenced by the current files object, not including the path, read-only.

2. Size: The size of the file, in bytes, and a read-only 64-bit integer.

3. type: MIME type, read-only string, or null if the type is unknown. Some mobile browsers obviously choose the picture, return is null, very pit.

There are also 3 non-standard methods:getasbinary(),Getasdataurl(), and Getastext(in domstring encoding).

These 3 methods are now obsolete and are now replaced with the methods in the FileReader object.

Iv. FileReader

A Web application can asynchronously read the contents of a file (or raw data buffer) stored on a user's computer , and can use a file object or Blob object to specify the files or data to be processed.

1) Readasarraybuffer(): The returned Result property will contain a ArrayBuffer object "Buffer array, which is a type used to render generic, fixed-length binary data" To represent the contents of the Read file

BLOBs can be "append", Arraybuffer data. The meaning of the existence of Arraybuffer is that it is written in memory as a data source in advance, which is nailed to an area in advance and fixed in length.

2) readasbinarystring(): The result property will contain the original binary data of the file being read

3) Readasdataurl(): The result property will contain a string in Data:url format to represent the contents of the Read file

4) Readastext(): The result property will contain a string representing the contents of the file being read

The following code is the fetch Data:url, which assigns the returned result content to the IMG SRC, which is used for previewing operations.

var New  function(e) {  varnew  Image ();    This . Result;  Console.log (this. result);};
The contents of Console.log (this. Result)   are as follows:

V. URL Object

The URL object is the URL to the file on your hard disk. The above example obtains a reference to a picture by reading the data Uri,data URI is a large string of characters.

Picture originally on the hard disk, but also to convert to another format, a bit around, can directly refer to the URL of the file, here are two methods:

1) URL. Createobjecturl (): Receives a reference to a file (file or Blob object) returns a URL object

2) URL. Revokeobjecturl (): Destroys the URL created

var url = url.createobjecturl (file); var New  =function(e) {  window. Url.revokeobjecturl (this// destroy }console.log (URL);

The contents of the Console.log (URL) are as follows:

You need to make a compatibility decision on the mobile side:

Window. URL = window. URL | | Window.webkiturl;

Six, BLOB objects

Blob(Binary large object) objects represent a piece of binary data, a class file object that contains read-only raw data.

The file interface is based on a blob, inherits the functionality of the Blob, and the extension supports local files on the user's computer.

1) 4 ways to create BLOB objects:

1. Call the Blob constructor

2. Use the slice () method on an existing Blob object to cut out another Blob object

3. Call the Toblob method on the Canvas object

4. The method of over-gas is created through the Blobbuilder interface, but the compatibility is not good, and the existing Blobbuilder implementations are prefixed

2) Use BLOB objects to generate downloadable files

var New Blob (["Pwstrick"]);  Add the Domstring object   to the array var a = document.createelement ("a" = Url.createobjecturl ( BLOB); // Create URL object a.download = "Test.txt";  HTML5 new Attribute   = "Test";            document.getElementsByTagName (' body ') [0].appendchild (a);

Generate a "a" label, and click on this link, you can download a txt text, the content is "Pwstrick".

3) Returns a new Blob object by using the slice method to block binary data by byte

Upload.addeventlistener (' Change ',function() {  varUpload = document.getElementById (' upload ');//each time you want to dynamically get  varFile = Upload.files[0]; varStart = 0; varChunk = 1024 * 10;//10KB  varEnd = Start +Chunk; varSize =file.size;  while(Start <size)    {Segment (file, start, end); Start=end; End= Start +Chunk; if(End >size) {End=size; }  }}, false);functionsegment (file, start, end) {varReader =NewFileReader (); Reader.onload=function(evt) {Console.log ([' Read bytes: ', start, '-', End].join ('));  }; varBlob =File.slice (start, end); Reader.readasbinarystring (BLOB);}

Seven, FormData

XMLHttpRequest Level 2 Adds a new interface, FormData.

With the Formdata object, you can use a key-value pair to simulate a complete form, and then use XMLHttpRequest to send the form.

The biggest advantage of using formdata is that we can upload a binary file asynchronously.

  var New FormData ();  Formdata.append ("name", "value"); // Common key-value pairs  // passing a Blob object  // passing a File object  var New XMLHttpRequest ();  Oreq.open ("POST", "http://xx.com");  Oreq.send (formData);

Resources:

Https://developer.mozilla.org/zh-CN/docs/Using_files_from_web_applications using files in a web App

http://javascript.ruanyifeng.com/htmlapi/file.html file and binary data operations

http://www.iunbug.com/archives/2012/06/04/208.html [Translate]javascript file Operations basics

http://www.iunbug.com/archives/2012/06/05/254.html [translate]javascript file Action URL Object

Http://www.html5rocks.com/zh/tutorials/file/dndfiles/using JavaScript to read files through the file API

Mobile picture operation (i)--upload

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.