Skip to content

Instantly share code, notes, and snippets.

@imchao9
Last active February 2, 2016 01:53
Show Gist options
  • Save imchao9/847072e5cb60b0526776 to your computer and use it in GitHub Desktop.
Save imchao9/847072e5cb60b0526776 to your computer and use it in GitHub Desktop.
上传头像到七牛
function uploadUserAvatar() {
var cdnUploadUrl = "http://up.qiniu.com";
getToken(uploadFile);
}
function getToken(callback) {
$.ajax({
url: apiServer+'/program/cdn/upload/token',
type:"get",
success: function(data) {
var token = data.data.token;
var fileKey = data.data.fileKey;
var file = $('#uploadAvatar')[0].files[0];
if(checkFile(file)) {
var formData = new FormData();
formData.append('token', token);
formData.append('file', file);
//formData.append('key',file.name);
callback(formData,getFile,fileKey);
}
}
})
}
function checkFile(file){
var result = true,isImg = false,
imgSetting = {
imgSize: 2097152, //2M
imgTypes: ["image/jpeg","image/png","image/bmp"]
};
for(var item in imgSetting.imgTypes) {
if(file.type == imgSetting.imgTypes[item]) {
isImg = true;
}
}
if(!isImg) {
alert("文件类型不对哦,只能是jpg,png,bmp");
result = false;
return result;
}
if(file.size > imgSetting.imgSize) {
alert("文件太大啦,不能超过2M哦!");
result = false;
return result;
}
return result;
}
function uploadFile(formData,callback,fileKey) {
$.ajax({
url: 'http://up.qiniu.com',
type: "post",
processData: false,
contentType: false,
data: formData,
success: function (data) {
console.log(data);
callback({filekey:fileKey});
}
})
}
function getFile(data) {
$.ajax({
url: apiServer+'/program/cdn/upload/fileurl',
type:"get",
data:data,
success: function(data) {
console.log(JSON.stringify(data));
var fileUrl = data.data.fileurl;
$('.avatar')[0].src = fileUrl;
}
})
}
var reader = new FileReader();
reader.onload = function () {
$('.avatar')[0].src = reader.result;
uploadUserAvatar();
};
$('#uploadAvatar').on('change', function () {
reader.readAsDataURL($('#uploadAvatar')[0].files[0]);
});
$('.avatar-upload-btn').on('click', function () {
$('#uploadAvatar').click();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment