-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
68 lines (65 loc) · 1.97 KB
/
main.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
function ajax(options){
options.start && options.start.call('start');
//执行上传操作
var xhr = new XMLHttpRequest();
xhr.open("post", options.url, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
returnDate = JSON.parse(xhr.responseText);
options.success && options.success.call('success', returnDate);
};
};
//表单数据
var fd = new FormData();
for (k in options.data) {
fd.append(k, options.data[k]);
}
options.file && fd.append('file', options.file);
//执行发送
result = xhr.send(fd);
}
var file = document.getElementById('file'),
image = document.getElementById('image'),
form = document.forms.upload_form;
function uploadImage(file){
ajax({
url: 'https://up-z2.qiniup.com',
data: {
file: file,
key: form.key.value,
'x:file_url': form.file_url.value,
token: form.token.value,
},
start: function(){
console.log('start to upload Image to Qiniu');
},
success: function(data){
// 给表单中的参数赋值
console.log(data);
image.src = data.file_url;
}
})
}
file.addEventListener('change', function(e){
var selected_file = e.target.files[0];
// 先请求服务器获取token
ajax({
url: './upload.php',
data: {
filename: selected_file.name
},
start: function(){
console.log('start to get uploadToken');
},
success: function(data){
// 给表单中的参数赋值
form.key.value = data.key;
form.file_url.value = data.fileurl+"/"+data.key;
form.token.value = data.token;
form.info.value = data.info;
// 执行上传图片操作
uploadImage(selected_file)
}
})
})