Created
July 24, 2018 07:40
-
-
Save xiaojue/6dd42306e5d7d946e764494195ef9f4d to your computer and use it in GitHub Desktop.
clipboard2img
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function clipboard2Img(options){ | |
var self = this; | |
this.URL = options.host + options.api; | |
this.success = options.success || function(){}; | |
if(!options.ele){ | |
return alert('options ele must have'); | |
} | |
options.ele.addEventListener('paste', self.getClipboardImage.bind(this), false) | |
} | |
clipboard2Img.prototype.getClipboardImage = function(e){ | |
var self = this; | |
var clipboard = e.clipboardData; | |
// 有无内容 | |
if (!clipboard.items || !clipboard.items.length) | |
{ | |
alert('未检测到剪切板内含有图片!') | |
return; | |
} | |
var temp; | |
if ((temp = clipboard.items[0]) && temp.type.match(/image/)) | |
{ | |
// 获取图片文件 | |
var imgFile = temp.getAsFile(); | |
var file = new FileReader(); | |
file.readAsDataURL(imgFile); | |
file.onload = function(e) | |
{ | |
var base64 = this.result | |
var blob = self.dataURItoBlob(base64) | |
var canvas = document.createElement('canvas'); | |
var dataURL = canvas.toDataURL('image/jpeg', 0.5); | |
var fd = new FormData(document.forms[0]); | |
fd.append("file", blob, 'image.png'); | |
self.uploadImage(fd) | |
} | |
} | |
else | |
{ | |
alert('未检测到剪切板内含有图片!') | |
} | |
} | |
// 将base64转blob对象 | |
clipboard2Img.prototype.dataURItoBlob = function(base64Data) { | |
var byteString; | |
if (base64Data.split(',')[0].indexOf('base64') >= 0) | |
byteString = atob(base64Data.split(',')[1]); | |
else | |
byteString = unescape(base64Data.split(',')[1]); | |
var mimeString = base64Data.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 | |
}); | |
} | |
clipboard2Img.prototype.uploadImage = function(formData) { | |
var self = this; | |
$.ajax( | |
{ | |
url: self.URL, | |
method: 'POST', | |
processData: false, // 必须 | |
contentType: false, // 必须 | |
dataType: 'json', | |
data: formData, | |
error:function(data){ | |
alert(data); | |
}, | |
success:function(data) { | |
var key = Object.keys(data)[0]; | |
var url = data[key]; | |
if (url) { | |
self.success(url); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment