PC Upload Image
Basic structure
- Form[enctype= "Multipart/form-data"]
- Input[type= "File"]
- Once the upload is complete, get the image URL and display it on the page
Problem
- The picture will be uploaded before it can be displayed
- Compress upload
H5 How to Solve
- FileReader
- Canvas
FileReader
FileReader can convert the file object to Base64, which gives you a first impression of the image and then handles the upload operation.
var fr = new FileReader();fr.readAsDataURL(file);fr.onload = function(e) { $(‘img‘).attr(‘src‘, e.target.result);};
FormData
The actual upload operation, mostly Ajax processing, formdata can be used to build form forms.
var fd = new FormData(); fd.append(‘filename‘, file);$.ajax({ url: ‘xxxx/yyyy‘, data: fd, type: ‘POST‘, cache: false, processData: false, contentType: false, dataType: ‘json‘, success: function(data) { }, error: function() { }});
Canvas
Mobile phone traffic is valuable, but upload a photo may have a few m, all need to compress the picture, canvas operation of the picture is processed through the base64 format.
var img = new Image();img.src = base64;img.onload = function(){ var canvas = document.createElement(‘canvas‘); canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; canvas.getContext("2d").drawImage(img, 0, 0); var compressBase64 = cvs.toDataURL(mime_type, quality / 100);}
Upload Base64
Use MQQ interface to take pictures or get local pictures, feedback is base64 format, input in the process, through compression and other operations may also convert the file object to Base64, Base64 upload support has the following scenarios:
- Server support, separate open Interface processing base64 upload
- The front end transforms the base64 into a file object, reusing the original server interface
The
focuses on the 2nd scenario. JS provides a Blob object, is a class file object, the file object inherits the Blob object, and makes some extensions.
Based on this, you just need to convert the Base64 into a Blob object. The construction reference of the blob here , you can use type data to handle it.
// 解码base64var byteString = atob(dataURI.split(‘,‘)[1]);var mimeString = dataURI.split(‘,‘)[0].split(‘:‘)[1].split(‘;‘)[0];// 类型数组var ia = new Uint8Array(byteString.length);for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i);}return new Blob([ia], { type: mimeString});
H5_PC Uploading Images