The H5 activity is very common, one form is to allow users to upload pictures to participate. The mobile terminal uploads pictures. Users generally upload pictures in the mobile phone album. Now the quality of the mobile phone is getting higher and higher. Generally, the size of the single photo is about 3m. If uploading is uploaded directly, it consumes a lot of traffic and the experience is not good. Therefore, before uploading, you need to compress the local area.
Next, summarize the compression uploaded function in the development of the H5 activity, and mark a few pits that have been stepped on, and share it with you:Xiaobai District Must -see
If there is no concept of mobile picture uploading, you need to supplement the three concepts of Filereader, Blob, and FormData.
1.Filereaderdefinition
Using the FileReader object, the web application can be asynchronous to read the file (or raw data buffer) stored on the user computer. You can use the File object or Blob object to specify the file or data you want to process.
method
Event processing procedure
use
Var filereader = New Filereader (); Filereader.onload = Function () {var url = this.Result;} // orfilereader.onLoad = Function (E) {var url = e.Target. result;} 2. BLOBBlob (Binary Large Object), a binary object, is a container that can store binary files.
3.FormDataUsing FormData object, you can use a series of key values to simulate a complete form, and then use XMLHTTPRequest to send this form.
Topic
Movement picture compression and upload process:1) INPUT FILE uploads pictures and read the picture uploaded by users with FileReader;
2) The picture data is transmitted into the IMG object, draws IMG to Canvas, and then uses Canvas.todataurl for compression;
3) Get the compressed base64 format image data, turn it into binary, plug into FormData, and finally submit FormData through XMLHTTPREQUEST
1. Get picture data Fileele.onChange = Function () {if (! This.Files.length) Return; // Consider the single picture situation var Judgment Whether it is the picture if (! /// (?: jpeg | png | gif) /i.test (_simpleFile.type)) return; // plugin exif.js to get iOS pictures var _Orientation; if (_ua.indexofxof ('iPhone')> 0) {exif.getdata (_simpleFile, Function () {_Orientation = exif.gettag (this, 'Orientation');} // 1. Read files, use FileReader to subdue the picture file. Converted into DataURL, that is, data: img/pNG; base64, the URL beginning can be placed directly in image.src; var _R_Reader = New FILEREADER (), _img = New Image (), _reader.onload = Function (). {_url = this.RSULT; _img.url = _URL; _img.OnLoad = Function () {var _data = compress (_img); uploadphoto (_data, _orientation);}; _READER. Readasdataurl (_simpleFile);}; 2. Compressed picture /** * Calculate the size of the picture, compress the size according to the size * 1. iPhone mobile phone html5 upload the picture direction problem, use exif.js * 2. Android UC browser does not support the new blob (), use blobbuilder * @param {Object} _img Image* @param {Number} _OnTATION Photo Information* @Return {String} Image pictures in Base64 Format*/Function Compress (_img, _Orientation) {// 2. Calculate the width value of the target size, if the high height of the picture uploads the picture of the picture Both are greater than the target chart, and compress the target map and other compression; if there is one side smaller, the ratio of uploading pictures is enlarged. VAR _GoalWidth = 750, // Target width_goalheight = 750, // Target height_Imgwidth = _img.naturWidth, // Image width_imgheight = _img.naturalHeight, // Picture height_Tempwi dth = _imgwidth, // zoom or shrink Temporary width_tempheight = _Imgheight, // The temporary width after zooming or reduction _R = 0; // Compression ratio if (_imgwidth ===_GoalWidth &&IMGHEIGHT ===_Goalheight) {} Else I f (_imgwidth> _goalwidth && _imgheight> _Goalheight) {// The width height is greater than the target chart, and equal compression is compressed _R = _imgwidth / _goalWidth; if (_imgheight / _goalheight < t;} _tempwidth = math.ceil (_imgwidth / _r ); imgwidth; if (_goalheight / _imgheight <_r) {_R = _Goalheight /_imgheight;}} Else {if (_imgwidth <_goalwidth) {// Small than _r = _goalwidth /_imgwidth;} Else {// small is less than _R = __R = __R = _ __R = __Goalheight /_ imgheight;}} _tempwidth = math.ceil (_imgwidth * _r); _tempheight = math.ceil (_imgheight * _R);} // 3. Use Canvas to cut the picture, and after the equalization or reduction of the cut VAR_CANVAS = E._ $ Get ('Canvas-CLIP' ); IF (! _ Canvas.getContext) Return; VAR _Context = _CANVAS.GetContext ('2D'); AR _Degree; // iOS BUG, you may encounter on your iPhone mobile phone Image direction error problem switch (_Orientation) {// iPhone horizontal screen shooting, at this time the home key is case 3: _Degree = 180; _tempwidth = -_ imgwidth; iPhone vertical screen shooting, this When the home key is below (the direction of the mobile phone normally) case 6: _canvas.width = _imgheight; _canvas.Height = _imgwidth; -_imgheight; Break; // iPhone vertical screen shooting, this When the home key is case 8: _canvas.width = _imgheight; _CANVAS.Height = _Imgwidth; _Degree = 270; _tempwidth = -_ IMGWIDTH; ght; break;} if (window.navigator.useragraphent.indexof ('iphone') > 0 && !! _ degree) {_Context.rotate (_degree*math.pi/180); Mage (_img, 0, 0, _tempwidth , _tempheight);} // TODATAURL method, you can obtain the format of the base64 picture information of the format: Image/PNG; Base64, ***; var _data = _Canvas.todataUrl ('Image/JPEG'); RetURN _data ;} 3. Upload pictures /** * Upload the picture to noS * @param {object} _blog blob format picture * @Return {void} */function uploadphoto (_data) {// 4. Get the picture information in Canvas //window.atob method will The picture of the base64 format is converted into a binary string; if the conversion value is directly assigned to the BLOB, it will report an error, and you need to be converted by the UINT8ARAY: finally create a blob object; _data = _data.split (',') [1]; Window.atob (_data); // If you do not use ArrayBuffer, the picture format sent to the server is [Object UINT8ARRAY], upload failure ... var _buffer = new arrayBuffer (_data.Length); VAR_UBUFFFER = Newt8ar ray (_buffer); for (var I = 0; I <_data.Length; I ++) {_ubuffer [i] = _data.charCodeat (i);} // Android uc browser does not support New blob (), use blobbuilder var _blob; try {_blob = new blob ([_ buffer], {type: 'image/jpeg'});} Catch (EE) {window.blobbuilder = window.blobbuilder || Window.webkitBlobbuilder || Window.m ozblobbuilder || window.msblobbuilder; if (if (if (if (if (if (if (if ( ee.Name == 'Typerror' && Window.blobbuilder) {var _bb = new blobbuilder (); _bb.append (_buffer); } VAR _Suffix = 'JPG' ; if (_blob.type === 'Image/JPEG') {_suffix = 'jpg';} // Get Nostoken this .__ Cache ._ $ requestdwrbyget , Param: [_suffix, ' ',' ',' ',' 1 '], onLoad: Function (_Tokens) {_tokens = _tokens || []; VAR _TOKEN = _TOKENS [0]; if (! _ Token ||! _Token.objectName ||! .uploadtoken) {Alert ('Token acquisition failed! '); Return false;} // Upload the picture to the nos var _ObjectName = _token.objectName, _uploadtoken = _token.uploadtoken, _bucketName = _Token.bucketName; _formdata = New FormData (); _FormData.append ('Object', _ObjectName) ; _formdata.append ('X-NOS-Token', _Uploadtoken); MlhttpRequest ();} else if ( Window.activexobject) {_xhr = New ActivexObject (Microsoft.xmlhttp);} _xhr.onReadyStateChange = Function () {if (_xhr.ReadyState === 4) {if (_xhr.status> = 200 && _xhr.status <300 ) || _xhr.status === 304) {var _imgurl = http://nos.netease.com/ + _bucketname +/ + _objectName +? ImageView; var _newurl = mb.x ._ $ imgressiziz e (_imgurl, 750, 750, 1, true); Window.location.href = 'http://www.lofter.com/act/taxiu?op=effect&ORIGIMGURL=' + _newurl; http : //nos.netease.com/ ' + _bucketname, true); _xhr.send (_formdata);}});}Determine the iphone shooting picture direction: EXIF
The above is the HTML5 mobile development picture compressed and uploading function introduced by Xiaobian to achieve the effect of simulation background data login. I hope it will be helpful to everyone. If you have any questions, please leave me a message. Xiaobian will reply to everyone in time. of. Thank you very much for your support for the VEVB Wulin website!