Home >Web Front-end >H5 Tutorial >Problems and solutions encountered in implementing simple image upload in HTML5 _html5 tutorial skills

Problems and solutions encountered in implementing simple image upload in HTML5 _html5 tutorial skills

WBOY
WBOYOriginal
2016-05-16 15:46:052005browse
1. Display
Because uploading files on the front end must go through the form, and ajax cannot be used. In this case, putting an input of type file into a mobile page really doesn’t look good, as shown below, which is very frustrating. Is there any

I searched for a solution. Some PCs replace this input with flash and use jquery tool libraries such as uploadify to do it. However, most browsers on the mobile side do not support flash. So the final method is to use the form form, just set the transparency of the form and input to 0, so that they and the content to be displayed are in the same div at the same time, and the displayed content can be made to look like you want. The code is as follows:

Copy the code
The code is as follows:








< /head>



Upload pictures








It looks like the picture above. It is displayed in the p tag of "Upload Image". Clicking it will have the effect of selecting file

2. JS code
My side It is quite simple to write, just using the basic function of h5 upload
The html code is as follows, action is the path to be requested, what I do here is upload and modify the avatar when the file changes, and enter the name of the tag The attributes cannot be omitted, they are specifically related to the backend interface

Copy the code
The code is as follows:




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("The file format must be an image");
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 interrupted
}, false);
oXHR.open('POST', actionUrl);
oXHR.send(vFD);
};

The above content has shared with you the relevant knowledge about the problems and solutions encountered in implementing simple image upload in HTML5. I hope it will be helpful to everyone.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn