Simply record this morning to do H5 upload some code and a pit
First, show
Because the front-end upload files must be through form form, can not use Ajax, so that a mobile page into a type file input is not really good-looking, the following figure, very frustrated there is no
Solution found that some of the PC is to replace this input into flash, the use of jquery tools library such as uploadify to do, but the mobile end of most browsers do not support Flash. So the final approach is to use form form forms, just the transparency of this form and input set to 0, so that they and the content to be displayed in a Div, the content can be displayed to make their own appearance. The code is as follows:
Look like this, the show is in the "upload picture" This p tag, click on it has the effect of selecting file
Second, JS code
I wrote this here is pretty simple, just use the next H5 upload basic functions
The HTML code is as follows, the action is to request the path, my side does is when the file changes to upload modifies the avatar, the input label's name attribute cannot omit, specifically with back-end interface related
<form id= "Uploadform" enctype= "Multipart/form-data" method= "post" action= "XXXXXX" >
<input type= "File" Name= "ImageFile" id= "ImageFile" onchange= "fileselected ()"/>
</form>
var imaxfilesize = 2097152; 2M
window.fileselected = function () {
var ofile = document.getElementById (' ImageFile '). Files[0]//Read file
var rfilter =/^ (Image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff) $/i;
if (!rfilter.test (Ofile.type)) {
alert ("File format must be picture");
return;
}
if (Ofile.size > Imaxfilesize) {
alert ("Picture size cannot exceed 2M");
return;
}
var VFD = new FormData (document.getElementById (' Uploadform ')),//Create request and data
OXHR = new XMLHttpRequest ();
Oxhr.addeventlistener (' Load ', function (resupload) {
//Success
}, false);
Oxhr.addeventlistener (' Error ', function () {
//Failed
}, false);
Oxhr.addeventlistener (' Abort ', function () {
//upload Interrupt
}, false);
Oxhr.open (' POST ', actionurl);
Oxhr.send (VFD);
};
Details determine success or failure, so do anything to be taken seriously.
The above is the entire content of this article, I hope to help you learn.