移动端图片上传方法
实现步骤
一、隐藏<input type="file" id="file" name="Filedata" style="display:none;" accept="image/*" />
二、创建上传按钮<div id="upload-box"></div>
三、绑定事件
$("#upload-box").click(function () {
$("#file").trigger("click");
})
插件代码jquery.uploadBase64.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
|
function
UploadBase64() {
this
.sw = 0;
this
.sh = 0;
this
.tw = 0;
this
.th = 0;
this
.scale = 0;
this
.maxWidth = 0;
this
.maxHeight = 0;
this
.maxSize = 0;
this
.fileSize = 0;
this
.fileDate =
null
;
this
.fileType =
''
;
this
.fileName =
''
;
this
.input =
null
;
this
.canvas =
null
;
this
.mime = {};
this
.type =
''
;
this
.callback =
function
() { };
this
.loading =
function
() { };
}
UploadBase64.prototype.init =
function
(options) {
this
.maxWidth = options.maxWidth || 800;
this
.maxHeight = options.maxHeight || 600;
this
.maxSize = options.maxSize || 3 * 1024 * 1024;
this
.input = options.input;
this
.mime = {
'png'
:
'image/png'
,
'jpg'
:
'image/jpeg'
,
'jpeg'
:
'image/jpeg'
,
'bmp'
:
'image/bmp'
};
this
.callback = options.callback ||
function
() { };
this
.loading = options.loading ||
function
() { };
this
._addEvent();
};
/**
* @description 绑定事件
* @param {Object} elm 元素
* @param {Function} fn 绑定函数
*/
UploadBase64.prototype._addEvent =
function
() {
var
_this =
this
;
function
tmpSelectFile(ev) {
_this._handelSelectFile(ev);
}
this
.input.addEventListener(
'change'
, tmpSelectFile,
false
);
};
/**
* @description 绑定事件
* @param {Object} elm 元素
* @param {Function} fn 绑定函数
*/
UploadBase64.prototype._handelSelectFile =
function
(ev) {
var
file = ev.target.files[0];
this
.type = file.type
// 如果没有文件类型,则通过后缀名判断(解决微信及360浏览器无法获取图片类型问题)
if
(!
this
.type) {
this
.type =
this
.mime[file.name.match(/\.([^\.]+)$/i)[1]];
}
if
(!/image.(png|jpg|jpeg|bmp)/.test(
this
.type)) {
alert(
'选择的文件类型不是图片'
);
return
;
}
if
(file.size >
this
.maxSize) {
alert(
'选择文件大于'
+
this
.maxSize / 1024 / 1024 +
'M,请重新选择'
);
return
;
}
this
.fileName = file.name;
this
.fileSize = file.size;
this
.fileType =
this
.type;
this
.fileDate = file.lastModifiedDate;
this
._readImage(file);
};
/**
* @description 读取图片文件
* @param {Object} image 图片文件
*/
UploadBase64.prototype._readImage =
function
(file) {
var
_this =
this
;
function
tmpCreateImage(uri) {
_this._createImage(uri);
}
this
.loading();
this
._getURI(file, tmpCreateImage);
};
/**
* @description 通过文件获得URI
* @param {Object} file 文件
* @param {Function} callback 回调函数,返回文件对应URI
* return {Bool} 返回false
*/
UploadBase64.prototype._getURI =
function
(file, callback) {
var
reader =
new
FileReader();
var
_this =
this
;
function
tmpLoad() {
// 头不带图片格式,需填写格式
var
re = /^data:base64,/;
var
ret =
this
.result +
''
;
if
(re.test(ret)) ret = ret.replace(re,
'data:'
+ _this.mime[_this.fileType] +
';base64,'
);
callback && callback(ret);
}
reader.onload = tmpLoad;
reader.readAsDataURL(file);
return
false
;
};
/**
* @description 创建图片
* @param {Object} image 图片文件
*/
UploadBase64.prototype._createImage =
function
(uri) {
var
img =
new
Image();
var
_this =
this
;
function
tmpLoad() {
_this._drawImage(
this
);
}
img.onload = tmpLoad;
img.src = uri;
};
/**
* @description 创建Canvas将图片画至其中,并获得压缩后的文件
* @param {Object} img 图片文件
* @param {Number} width 图片最大宽度
* @param {Number} height 图片最大高度
* @param {Function} callback 回调函数,参数为图片base64编码
* return {Object} 返回压缩后的图片
*/
UploadBase64.prototype._drawImage =
function
(img, callback) {
this
.sw = img.width;
this
.sh = img.height;
this
.tw = img.width;
this
.th = img.height;
this
.scale = (
this
.tw /
this
.th).toFixed(2);
if
(
this
.sw >
this
.maxWidth) {
this
.sw =
this
.maxWidth;
this
.sh = Math.round(
this
.sw /
this
.scale);
}
if
(
this
.sh >
this
.maxHeight) {
this
.sh =
this
.maxHeight;
this
.sw = Math.round(
this
.sh *
this
.scale);
}
this
.canvas = document.createElement(
'canvas'
);
var
ctx =
this
.canvas.getContext(
'2d'
);
this
.canvas.width =
this
.sw;
this
.canvas.height =
this
.sh;
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0,
this
.sw,
this
.sh);
this
.callback(
this
.canvas.toDataURL(
this
.type));
ctx.clearRect(0, 0,
this
.tw,
this
.th);
this
.canvas.width = 0;
this
.canvas.height = 0;
this
.canvas =
null
;
};
|
HTML代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
<!
doctype
html>
<
html
>
<
head
>
<
meta
charset="utf-8">
<
meta
name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<
title
>手机端图片上传</
title
>
</
head
>
<
body
>
<
script
type="text/javascript" charset="utf-8" src="/scripts/jquery/jquery-1.11.2.min.js"></
script
>
<
script
src="scripts/jquery/jquery.uploadBase64.js" type="text/javascript"></
script
>
<
input
type="file" accept="image/*" id="file" style="display:none">
<
div
id="upload-box" style="width:200px;height:45px;line-height:45px;text-align:center;color:#fff; background:#02598e; cursor:pointer;">移动端图片上传</
div
>
<
script
>
document.addEventListener('DOMContentLoaded', init, false);
function init() {
var u = new UploadBase64();
u.init({
input: document.querySelector('#file'),
callback: function (base64) {
$.ajax({
url: "/upload_ajax.ashx?action=UploadBase64",
data: { base64: base64, type: this.fileType },
type: 'post',
dataType: 'json',
success: function (i) {
alert(i.info);
}
})
},
loading: function () {
}
});
}
$(function () {
$("#upload-box").click(function () {
$("#file").trigger("click");
})
})
</
script
>
</
body
>
</
html
>
|
asp.net后台处理代码:upload_ajax.ashx
using
System;
using
System.Collections;
using
System.IO;
using
System.Collections.Generic;
using
System.Web.SessionState;
using
System.Web;
using
System.Drawing;
namespace
DianShang.Web.tools
{
/// <summary>
/// 文件上传处理页
/// </summary>
public
class
upload_ajaxs : IHttpHandler, IRequiresSessionState
{
public
void
ProcessRequest(HttpContext context)
{
//取得处事类型
string
action = context.Request.QueryString[
"action"
];
switch
(action)
{
case
"UpLoadBase64"
:
//Base64编码上传
UpLoadBase64(context);
break
;
default
:
//普通上传
UpLoadFile(context);
break
;
}
}
#region Base64编码上传===================================
private
void
UpLoadBase64(HttpContext context)
{
Model.siteconfig siteConfig =
new
BLL.siteconfig().loadConfig();
string
_delpath = context.Request.Form[
"delpath"
];
string
_upfile = context.Request.Form[
"base64"
];
string
[] tmpArr = _upfile.Split(
','
);
byte
[] base64 = Convert.FromBase64String(tmpArr[1]);
MemoryStream ms =
new
MemoryStream(base64);
System.Drawing.Image postedFile = System.Drawing.Image.FromStream(ms);
string
path = String.Format(
"/upload/{0}/{0}.jpg"
, DateTime.Now.ToString(
"yyyyMMddHHss"
));
//保存文件
postedFile.Save(context.Server.MapPath(path));
//处理完毕,返回JOSN格式的文件信息
context.Response.Write(
"{\"status\": 1, \"msg\": \"上传文件成功!\", \"path\": \""
+ path +
"\"}"
);
context.Response.End();
}
#endregion
#region 普通上传===================================
private
void
UpLoadFile(HttpContext context)
{
}
#endregion
public
bool
IsReusable
{
get
{
return
false
;
}
}
}
}
|
"唯有高屋建瓴,方可水到渠成"