How to use H5 to upload pictures

php中世界最好的语言
Release: 2018-06-04 11:20:00
Original
8452 people have browsed it

This time I will bring you how to use H5 to upload pictures and how to use H5 to upload pictures.NotesYes Which ones, the following are practical cases, let’s take a look.

I worked on a project a few days ago, and one of the modules involved uploading images to the server. I took the time to sort it out today, and found that the more I sorted it out, the more knowledge points it involved. The following examples refer to Baidu’s image search.

Knowledge points: input file, base64, FileReader, canvas compression, blob, btoa encoding and atob decoding, FormData.

html dom node:

Copy after login

A file can be selected by default. Multiple photos need to be uploaded. You can add the multiple="true" attribute. Generally use opacity:0; to hide the default style, and then rewrite its style.

1. Create object

var fileReader = new FileReader();

2. Determine whether the browser is compatible----it is not supported under ie8

if(window.FileReader)

3. Status constant

##1 File reading DONE 2 File Reading completed
Constant name Value Description
EMPTY 0 is the beginningReading file
##LOADING
#In the following example, the current status can be read separately.

4. Attribute

5. Method

##Attribute name error readyState result
Description
An error occurred while reading the file
The state of the current fileReader object is one of the above state constants
Read content
##blob/file read It is dataUrl, and there is a string in the data:url format in the result that represents the read content readAsTexx blob/file, [encoding] is read as text, and the string in the result represents the read content
Method name Parameters Description
abort None Abort reading, calling in non-LOADING state willthrow an exception
##readAsArrayBuffer blob/file Read as an array, there is an ArrayBuffer object in the result for the read content
readAsBinaryString blob/file Read as binary, there is a function to read the file in the result Raw binary
readAsDataUrl
6. Event handling

BASE64:

我们用chrome打开一张图片,在resources里面显示的就是图片的base编码(实际上base编码比原图片稍大)

图片的base64编码也就是将一张图片编码成一个字符串,我们可以用这个字符串给img标签的src赋值,这样我们就可以看到这张图片。

如何编写:

在html中:

Copy after login

在css中:

background-image:url(data:image/gif;base64,R0lGODlhBAABAIABAMLBwfLx8SH5BAEAAAEALAAAAAAEAAEAAAICRF4AOw==);
Copy after login

优缺点:

优点:1、减少了http请求;2、可以被gzip;3、没有跨域问题;4、无需考虑在更新图片时缓存问题。

缺点:1、ie8以下不支持;2、不论是写在css文件还是html文件中,增加了文件的大小;3、图片大了之后,程序员编码相当困难;

应用:

根据实际需求来选择base64显示图片,或者选择css sprite,或者直接使用png等

一般使用场景:很少被更新,实际尺寸很小,在系统中大量使用。

canvas压缩:

在移动应用场景中,用户上传的图片一般很大,会导致上传时间过长而失败,既浪费时间也浪费流量,更影响用户体验。我们可以使用canvas的drawImage方法的图形裁剪功能。

1、新建image对象,给其src复制base64值,在其监听onload事件;

2、在onload事件方法中新建canvas对象,获取上下文context;

3、设置裁剪比例,调用drawImage方法填充图片。

4、通过toDataUrl方法获取裁剪之后的base64值。

详细见下例。

Blob

在传输一些比较大的图片的base64是容易出现转发错误,这里我们可以将base64转换成blob字段写到form表单中提交到后台。一般blob和base64之间的相互转换通过fileReader 的readAsDataUrl和ArrayBuffer的charCodeAt方法。下面列举几个相互转换的方法。来自(http://jsperf.com/blob-base64-conversion)

 var blobToBase64 = function(blob, cb) {
var reader = new FileReader();
reader.onload = function() {
var dataUrl = reader.result;
var base64 = dataUrl.split(',')[1];
cb(base64);
};
reader.readAsDataURL(blob);
};
var base64ToBlob = function(base64, cb) {
var binary = atob(base64);
var len = binary.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
view[i] = binary.charCodeAt(i);
}
cb(new Blob([view]));
};
var base64ToBlobSync = function(base64) {
var binary = atob(base64);
var len = binary.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
view[i] = binary.charCodeAt(i);
}
var blob = new Blob([view]);
return blob;
};
var blobToBase64_2 = function(blob, cb) {
var reader = new FileReader();
reader.onload = function() {
var buffer = reader.result;
var view = new Uint8Array(buffer);
var binary = String.fromCharCode.apply(window, view);
var base64 = btoa(binary);
cb(base64);
};
reader.readAsArrayBuffer(blob);
};
Copy after login

btoa 与 atob: ---在对base64转blob时就需要用atob对base64进行解码

btoa("javascript"); //"amF2YXNjcmlwdA==" atob("amF2YXNjcmlwdA==") ; //"javascript"
Copy after login

注意:在需要转码中文时,需要用encodeURIComponent方法对中文处理,解码时用decodeURIComponent

btoa(encodeURIComponent("我喜欢 javascript")); //"JUU2JTg4JTkxJUU1JTk2JTlDJUU2JUFDJUEyJTIwamF2YXNjcmlwdA==" decodeURIComponent(atob("JUU2JTg4JTkxJUU1JTk2JTlDJUU2JUFDJUEyJTIwamF2YXNjcmlwdA==")); //"我喜欢 javascript" FormData:
Copy after login

我们只需要使用new FormData()创建对象,然后append键值对,后用ajax向后台发生即可。

这里是往FormData对象添加blob字段。

注:使用Ajax将这个FormData对象提交到服务器上时,所发送的HTTP请求头中代表那个Blob对象所包含文件的文件名称的"Content-Disposition"请求头的值会是一个空字符串,这会引发某些服务器程序上的错误.从Gecko 7.0开始,这种情况下发送的文件名称改为"blob"这个字符串.

     Document   

拍摄

Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

JS中特性与UA检测

Ajax的工作原理核心以及对象

Event Description onabort Triggered on interrupt onerror Triggered when an error occurs onload Triggered when the read is successful onloadend Triggered when the read is completed (regardless of success) onloadstart Fires when reading starts onprocess Triggered while reading

The above is the detailed content of How to use H5 to upload pictures. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!